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

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

我怎么做呢?


当前回答

appHelper.validateDates = function (start, end) {
    var returnval = false;

    var fd = new Date(start);
    var fdms = fd.getTime();
    var ed = new Date(end);
    var edms = ed.getTime();
    var cd = new Date();
    var cdms = cd.getTime();

    if (fdms >= edms) {
        returnval = false;
        console.log("step 1");
    }
    else if (cdms >= edms) {
        returnval = false;
        console.log("step 2");
    }
    else {
        returnval = true;
        console.log("step 3");
    }
    console.log("vall", returnval)
    return returnval;
}

其他回答

总的来说,我并不反对图书馆。在这种情况下,通用库似乎有些多余,除非应用程序过程的其他部分过时得很严重。

编写这样的小实用函数对于初学者和熟练的程序员来说都是一个有用的练习,对于我们中的新手来说也是一个学习经验。

function dateFormat (date, fstr, utc) {
  utc = utc ? 'getUTC' : 'get';
  return fstr.replace (/%[YmdHMS]/g, function (m) {
    switch (m) {
    case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
    case '%m': m = 1 + date[utc + 'Month'] (); break;
    case '%d': m = date[utc + 'Date'] (); break;
    case '%H': m = date[utc + 'Hours'] (); break;
    case '%M': m = date[utc + 'Minutes'] (); break;
    case '%S': m = date[utc + 'Seconds'] (); break;
    default: return m.slice (1); // unknown code, remove %
    }
    // add leading zero if required
    return ('0' + m).slice (-2);
  });
}

/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns 
   "2012-05-18 05:37:21"  */

UPDATE 2021-10-06: Added Day.js and remove spurious edit by @ashleedawg UPDATE 2021-04-07: Luxon added by @Tampa. UPDATE 2021-02-28: It should now be noted that Moment.js is no longer being actively developed. It won't disappear in a hurry because it is embedded in so many other things. The website has some recommendations for alternatives and an explanation of why. UPDATE 2017-03-29: Added date-fns, some notes on Moment and Datejs UPDATE 2016-09-14: Added SugarJS which seems to have some excellent date/time functions.


好吧,既然还没有人给出真正的答案,那我的答案就是。

库当然是以标准方式处理日期和时间的最佳选择。在日期/时间计算中有许多边缘情况,因此能够将开发移交给库是非常有用的。

以下是主要Node兼容的时间格式化库列表:

Day.js [added 2021-10-06] "Fast 2kB alternative to Moment.js with the same modern API" Luxon [added 2017-03-29, thanks to Tampa] "A powerful, modern, and friendly wrapper for JavaScript dates and times." - MomentJS rebuilt from the ground up with immutable types, chaining and much more. Moment.js [thanks to Mustafa] "A lightweight (4.3k) javascript date library for parsing, manipulating, and formatting dates" - Includes internationalization, calculations and relative date formats - Update 2017-03-29: Not quite so light-weight any more but still the most comprehensive solution, especially if you need timezone support. - Update 2021-02-28: No longer in active development. date-fns [added 2017-03-29, thanks to Fractalf] Small, fast, works with standard JS date objects. Great alternative to Moment if you don't need timezone support. SugarJS - A general helper library adding much needed features to JavaScripts built-in object types. Includes some excellent looking date/time capabilities. strftime - Just what it says, nice and simple dateutil - This is the one I used to use before MomentJS node-formatdate TimeTraveller - "Time Traveller provides a set of utility methods to deal with dates. From adding and subtracting, to formatting. Time Traveller only extends date objects that it creates, without polluting the global namespace." Tempus [thanks to Dan D] - UPDATE: this can also be used with Node and deployed with npm, see the docs

还有一些非node库:

Datejs[感谢Peter Olson] -没有打包在npm或GitHub中,所以不太容易与Node一起使用-不太推荐,因为自2007年以来没有更新!

我需要一个简单的格式化库,不需要locale和语言支持。所以我修改了

http://www.mattkruse.com/javascript/date/date.js

并且使用它。参见https://github.com/adgang/atom-time/blob/master/lib/dateformat.js

文档非常清楚。

你可以使用轻量级库Moment js

npm install moment

给图书馆打电话

var moments = require("moment");

现在转换成你需要的格式

moment().format('MMMM Do YYYY, h:mm:ss a');

更多格式和细节,你可以关注官方文档Moment js

如果你使用Node.js,你肯定有EcmaScript 5,所以Date有一个toISOString方法。您要求对ISO8601进行轻微修改:

new Date().toISOString()
> '2012-11-04T14:51:06.157Z'

所以只要剪掉一些东西,你就搞定了:

new Date().toISOString().
  replace(/T/, ' ').      // replace T with a space
  replace(/\..+/, '')     // delete the dot and everything after
> '2012-11-04 14:55:45'

或者,在一行中:new Date(). toisostring()。replace(/T/, ' ').replace(/\..+ /”)

ISO8601必然是UTC(也由第一个结果的末尾Z表示),因此默认情况下得到UTC(总是一件好事)。