使用NodeJS,我想将Date格式化为以下字符串格式:

var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");

我怎么做呢?


当前回答

我认为这实际上回答了你的问题。 在javascript中处理日期/时间是很烦人的。 在我长了几根白头发之后,我发现这其实很简单。

var date = new Date();
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();

var ampm = hours >= 12 ? 'pm' : 'am';
hours = ((hours + 11) % 12 + 1);//for 12 hour format

var str = month + "/" + day + "/" + year + " " + hours + ":" + min + ":" + sec + " " + ampm;
var now_utc =  Date.UTC(str);

这里有一把小提琴

其他回答

易于阅读和自定义的方式,以获得所需格式的时间戳,无需使用任何库:

function timestamp(){
  function pad(n) {return n<10 ? "0"+n : n}
  d=new Date()
  dash="-"
  colon=":"
  return d.getFullYear()+dash+
  pad(d.getMonth()+1)+dash+
  pad(d.getDate())+" "+
  pad(d.getHours())+colon+
  pad(d.getMinutes())+colon+
  pad(d.getSeconds())
}

(如果您需要UTC格式的时间,那么只需更改函数调用。例如"getMonth"变成"getUTCMonth")

我在Nodejs和angularjs中使用dateformat,很好

安装

$ npm install dateformat
$ dateformat --help

demo

var dateFormat = require('dateformat');
var now = new Date();

// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21

// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!

// You can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
...

在反映你的时区时,你可以使用这个

新日期() 新日期( 时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制。时间限制 ); var curr_time = dateString.toISOString()。代表(“T”,“”)。substr (0, 19); 游戏机。log (curr_time);

现代网络浏览器(和Node.js)通过Intl对象公开国际化和时区支持,该对象提供了一个Intl. datetimeformat .prototype. formattoparts()方法。

您可以在没有添加库的情况下执行以下操作:

function format(dateObject){ let dtf = new Intl.DateTimeFormat("en-US", { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }); var parts = dtf.formatToParts(dateObject); var fmtArr = ["year","month","day","hour","minute","second"]; var str = ""; for (var i = 0; i < fmtArr.length; i++) { if(i===1 || i===2){ str += "-"; } if(i===3){ str += " "; } if(i>=4){ str += ":"; } for (var ii = 0; ii < parts.length; ii++) { let type = parts[ii]["type"] let value = parts[ii]["value"] if(fmtArr[i]===type){ str = str += value; } } } return str; } console.log(format(Date.now()));

有一个转换库:

npm install dateformat

然后写下你的要求:

var dateFormat = require('dateformat');

然后绑定值:

var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");

看到dateformat