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

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

我怎么做呢?


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

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

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年以来没有更新!


如果你使用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(总是一件好事)。


使用Date对象提供的方法,如下所示:

var ts_hms = new Date();

console.log(
    ts_hms.getFullYear() + '-' + 
    ("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' + 
    ("0" + (ts_hms.getDate())).slice(-2) + ' ' +
    ("0" + ts_hms.getHours()).slice(-2) + ':' +
    ("0" + ts_hms.getMinutes()).slice(-2) + ':' +
    ("0" + ts_hms.getSeconds()).slice(-2));

它看起来很脏,但它应该可以很好地与JavaScript核心方法一起工作


javascript库sugar.js (http://sugarjs.com/)有格式化日期的函数

例子:

Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')

有一个转换库:

npm install dateformat

然后写下你的要求:

var dateFormat = require('dateformat');

然后绑定值:

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

看到dateformat


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

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

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

文档非常清楚。


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

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")


使用x-date模块,它是x类库的子模块之一;

require('x-date') ; 
  //---
 new Date().format('yyyy-mm-dd HH:MM:ss')
  //'2016-07-17 18:12:37'
 new Date().format('ddd , yyyy-mm-dd HH:MM:ss')
  // 'Sun , 2016-07-17 18:12:51'
 new Date().format('dddd , yyyy-mm-dd HH:MM:ss')
 //'Sunday , 2016-07-17 18:12:58'
 new Date().format('dddd ddSS of mmm , yy')
  // 'Sunday 17thth +0300f Jul , 16'
 new Date().format('dddd ddS  mmm , yy')
 //'Sunday 17th  Jul , 16'

new Date(2015,1,3,15,30).toLocaleString()

//=> 2015-02-03 15:30:00

new Date().toString("yyyyMMddHHmmss").
      replace(/T/, ' ').  
      replace(/\..+/, '') 

使用.toString(),这将变成格式 replace(/T/, ' ')。//替换T到' ' 2017-01-15T… 替换(/ . .+/, ") //for…13:50:16.1271

示例:参见var date and hour:

var日期”=“2017-01-15T13:50:16 1271。”“yyyyMMddHHmmss”toString()。 代表(/T/, ')。 replace(/)。+ / -); var auxCopia =日期。斯普利特(“”); 鉴于= auxCopia [0]; var时光= auxCopia [1]; 游戏机。log(日期); 游戏机。log(时光”);


我认为这实际上回答了你的问题。 在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);

这里有一把小提琴


我在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
...

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;
}

替代# 6233…

将UTC偏移量添加到本地时间,然后使用Date对象的toLocaleDateString()方法将其转换为所需的格式:

// Using the current date/time
let now_local = new Date();
let now_utc = new Date();

// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())

// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';

// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));

我正在创建一个默认为本地时间的日期对象。我添加了UTC偏移量。我正在创建一个日期格式化对象。我正在以所需的格式显示UTC日期/时间:


对于日期格式,最简单的方法是使用moment lib。https://momentjs.com/

const moment = require('moment')
const current = moment().utc().format('Y-M-D H:M:S')

检查下面的代码和到Date Object, Intl的链接。DateTimeFormat

// var ts_hms = new Date(UTC); // ts_hms.format("%Y-%m-%d %H:%M:%S") // exact format console.log(new Date().toISOString().replace('T', ' ').substring(0, 19)) // other formats console.log(new Date().toUTCString()) console.log(new Date().toLocaleString('en-US')) console.log(new Date().toString()) // log format const parts = new Date().toString().split(' ') console.log([parts[1], parts[2], parts[4]].join(' ')) // intl console.log(new Intl.DateTimeFormat('en-US', {dateStyle: 'long', timeStyle: 'long'}).format(new Date()))


这是我写的一个轻量级的简单日期格式库,可以在node.js和浏览器上运行

安装

使用NPM安装

npm install @riversun/simple-date-format

or

直接加载(浏览器),

<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format/lib/simple-date-format.js"></script>

加载库

ES6

import SimpleDateFormat from "@riversun/simple-date-format";

CommonJS node.js)

const SimpleDateFormat = require('@riversun/simple-date-format');

Usage1

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"

用钢笔跑

Usage2

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
console.log(sdf.format(date));//to be "2018-07-17T12:08:56+09:00"

格式化模式

https://github.com/riversun/simple-date-format#pattern-of-the-date


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

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


从“日期格式”导入日期格式; var what = new Date()

<footer>
    <span>{props.data.footer_desc} <a href={props.data.footer_link}>{props.data.footer_text_link}</a> {" "}
    ({day = dateFormat(props.data.updatedAt, "yyyy")})
            </span>
</footer>

rodape


这里有一个方便的香草单行(改编自此):

Var timestamp = new Date((dt = new Date()).getTime() - dt. gettimezoneoffset () * 60000) .toISOString () .replace (/ (. *), (. *) \ T . .* /, ' $ 1 $ 2 ') console.log(时间戳)

输出:2022-02-11 11:57:39


用Date就可以很容易地解决这个问题。

function getDateAndTime(time: Date) {
  const date = time.toLocaleDateString('pt-BR', {
    timeZone: 'America/Sao_Paulo',
  });
  const hour = time.toLocaleTimeString('pt-BR', {
    timeZone: 'America/Sao_Paulo',
  });
  return `${date} ${hour}`;
}

这是为了显示:// 10/31/22 11:13:25


现代网络浏览器(和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()));


你可以使用轻量级库Moment js

npm install moment

给图书馆打电话

var moments = require("moment");

现在转换成你需要的格式

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

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