简体   繁体   English

在javascript中打印日期,如“Ymd H:i:s”

[英]print date like 'Y-m-d H:i:s"in javascript

Is there a built in way in javascript that formats a date object in a format like “Ymd H:i:s”? javascript 中是否有一种内置方式可以将日期对象格式化为“Ymd H:i:s”之类的格式?

I use我用

var since= new Date(xhr.getResponseHeader("Last-Modified"));
alert("modified:: " +since.getDate()+'.'+(since.getMonth()+1)+'. '+ since.getHours()+':'+since.getMinutes())

But that cuts off all leading zeros但这会切断所有前导零

You can try this:你可以试试这个:

function LeadingZero(s,max) {
    var z = max-s.length+1;
    z = z>1 ? Array(z).join('0') : '';
    return (z + s);     
}

alert("modified:: " +LeadingZero(since.getDate(),2)+'.'+LeadingZero(since.getMonth()+1,2)+'. '+ LeadingZero(since.getHours(),2));

But I recommend using Moment.js , a library for handling dates in JS.但我推荐使用Moment.js ,一个在 JS 中处理日期的库。 It has built in a formatter and can do a lot of other stuff.它内置了一个格式化程序,可以做很多其他的事情。

In moment you can do it this way:现在你可以这样做:

var d = moment(since);
alert(d.format('YYYY-MM-DD HH:mm:ss'));

Use this function:使用这个功能:

function pad(number) {
  if ( number < 10 ) {
    return '0' + number;
  }
  return number;
}

pad(since.getDate())+'.'+pad(since.getMonth()+1)+'. '+ pad(since.getHours())+':'+pad(since.getMinutes())

For Ymd H:i:s format use following example:对于 Ymd H:i:s 格式,请使用以下示例:

pad(since.getFullYear()) + '-' + pad(since.getMonth()+1) + '-' + pad(since.getDate()) + ' ' + pad(since.getHours()) + ':' + pad(since.getMinutes()) + ':' + pad(since.getSeconds())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM