javascript日期到字符串 [英] javascript date to string

查看:134
本文介绍了javascript日期到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我需要做的。



获取日期,转换为字符串并将其传递给第三方实用程序。
当我传递它时,库的响应将以字符串格式显示日期。所以,我需要将日期转换为字符串像20110506105524(YYYYMMDDHHMMSS)

  function printDate(){
var temp = new Date();
var dateStr = temp.getFullYear()。toString()+
temp.getMonth()。toString()+
temp.getDate()。toString()+
temp .getHours()。toString()+
temp.getMinutes()。toString()+
temp.getSeconds()。toString();

调试(dateStr);
}

上面的问题是,对于1-9个月,它打印一位数字。如何更改它以打印2个数字的月份,日期...

解决方案

您将需要用0 如果它的一位数字注意 getMonth 返回0..11不是1..12

 函数printDate(){
var temp = new Date();
var dateStr = padStr(temp.getFullYear())+
padStr(1 + temp.getMonth())+
padStr(temp.getDate())+
padStr temp.getHours())+
padStr(temp.getMinutes())+
padStr(temp.getSeconds());
debug(dateStr);
}

function padStr(i){
return(i< 10)? 0+ i:+ i;
}


Here is what I need to do.

Get Date, convert to string and pass it over to a third party utility. The response from the library will have date in string format as I passed it. So, I need to convert the date to string like 20110506105524 (YYYYMMDDHHMMSS)

function printDate() {
    var temp = new Date();
    var dateStr = temp.getFullYear().toString() + 
                  temp.getMonth().toString() + 
                  temp.getDate().toString() +
                  temp.getHours().toString() + 
                  temp.getMinutes().toString() + 
                  temp.getSeconds().toString();

    debug (dateStr );
}

The problem with above is that for months 1-9, it prints one digit. How can I change it to print exactly 2 digits for month, date ...

解决方案

You will need to pad with "0" if its a single digit & note getMonth returns 0..11 not 1..12

function printDate() {
    var temp = new Date();
    var dateStr = padStr(temp.getFullYear()) +
                  padStr(1 + temp.getMonth()) +
                  padStr(temp.getDate()) +
                  padStr(temp.getHours()) +
                  padStr(temp.getMinutes()) +
                  padStr(temp.getSeconds());
    debug (dateStr );
}

function padStr(i) {
    return (i < 10) ? "0" + i : "" + i;
}

这篇关于javascript日期到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆