简体   繁体   English

如何使用 NodeJS 将 UTC 日期格式化为“YYYY-MM-DD hh:mm:ss”字符串?

[英]How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?

Using NodeJS, I want to format a Date into the following string format:使用 NodeJS,我想将Date格式化为以下字符串格式:

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

How do I do that?我怎么做?

If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method.如果你使用 Node.js,你肯定有 EcmaScript 5,所以 Date 有一个toISOString方法。 You're asking for a slight modification of ISO8601:您要求对 ISO8601 稍作修改:

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

So just cut a few things out, and you're set:所以只要删掉一些东西,你就准备好了:

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

Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\\..+/, '')或者,在一行中: new Date().toISOString().replace(/T/, ' ').replace(/\\..+/, '')

ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing). ISO8601 必须是 UTC(也由第一个结果的尾随 Z 表示),因此默认情况下您会获得 UTC(总是一件好事)。

UPDATE 2021-10-06: Added Day.js and remove spurious edit by @ashleedawg更新 2021-10-06:添加了 Day.js 并删除了@ashleedawg 的虚假编辑
UPDATE 2021-04-07: Luxon added by @Tampa.更新 2021-04-07:@Tampa 添加了 Luxon。
UPDATE 2021-02-28: It should now be noted that Moment.js is no longer being actively developed.更新 2021-02-28:现在应该注意 Moment.js 不再被积极开发。 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更新 2017-03-29:添加了 date-fns,关于 Moment 和 Datejs 的一些注释
UPDATE 2016-09-14: Added SugarJS which seems to have some excellent date/time functions. 2016 年 9 月 14 日更新:添加了 SugarJS,它似乎具有一些出色的日期/时间功能。


OK, since no one has actually provided an actual answer, here is mine.好的,因为没有人真正提供过实际的答案,这里是我的。

A library is certainly the best bet for handling dates and times in a standard way.图书馆无疑是以标准方式处理日期和时间的最佳选择。 There are lots of edge cases in date/time calculations so it is useful to be able to hand-off the development to a library.日期/时间计算中有很多边缘情况,因此能够将开发移交给库很有用。

Here is a list of the main Node compatible time formatting libraries:以下是主要的Node兼容时间格式库的列表:

  • Day.js [ added 2021-10-06 ] "Fast 2kB alternative to Moment.js with the same modern API" Day.js [ 2021-10-06添加]“具有相同现代 API 的 Moment.js 的快速 2kB 替代品”
  • Luxon [ added 2017-03-29, thanks to Tampa ] "A powerful, modern, and friendly wrapper for JavaScript dates and times." Luxon [ 2017-03-29 添加,感谢 Tampa ] “一个强大、现代且友好的 JavaScript 日期和时间包装器。” - MomentJS rebuilt from the ground up with immutable types, chaining and much more. - MomentJS 使用不可变类型、链接等从头开始重建。
  • 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. Moment.js [感谢 Mustafa ] “用于解析、操作和格式化日期的轻量级 (4.3k) javascript 日期库” - 包括国际化、计算和相关日期格式 -更新 2017-03-29 :不太轻量级更多但仍然是最全面的解决方案,特别是如果您需要时区支持。 - Update 2021-02-28 : No longer in active development. - 2021-02-28 更新:不再积极开发。
  • date-fns [ added 2017-03-29, thanks to Fractalf ] Small, fast, works with standard JS date objects. date-fns [ 2017 年 3 月 29添加,感谢 Fractalf ] 小巧、快速,适用于标准 JS 日期对象。 Great alternative to Moment if you don't need timezone support.如果您不需要时区支持,则是 Moment 的绝佳替代品。
  • SugarJS - A general helper library adding much needed features to JavaScripts built-in object types. SugarJS - 一个通用的辅助库,为 JavaScript 的内置对象类型添加了急需的功能。 Includes some excellent looking date/time capabilities.包括一些出色的日期/时间功能。
  • strftime - Just what it says, nice and simple strftime - 正如它所说的那样,漂亮而简单
  • dateutil - This is the one I used to use before MomentJS dateutil - 这是我在 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." TimeTraveller - “Time Traveler 提供了一组实用方法来处理日期。从加法和减法到格式化。Time Traveler 只扩展它创建的日期对象,而不会污染全局命名空间。”
  • Tempus [ thanks to Dan D ] - UPDATE: this can also be used with Node and deployed with npm, see the docs Tempus [感谢 Dan D ] - 更新:这也可以与 Node 一起使用并与 npm 一起部署,请参阅文档

There are also non-Node libraries:还有非节点库:

  • Datejs [ thanks to Peter Olson ] - not packaged in npm or GitHub so not quite so easy to use with Node - not really recommended as not updated since 2007! Datejs [感谢 Peter Olson ] - 没有打包在 npm 或 GitHub 中,所以不太容易与 Node 一起使用 - 不推荐,因为自 2007 年以来没有更新!

There's a library for conversion:有一个用于转换的库:

npm install dateformat

Then write your requirement:然后写出你的需求:

var dateFormat = require('dateformat');

Then bind the value:然后绑定值:

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

see dateformat见日期格式

I have nothing against libraries in general.我一般不反对图书馆。 In this case a general purpose library seems overkill, unless other parts of the application process dates heavily.在这种情况下,通用库似乎过大了,除非申请过程的其他部分过时。

Writing small utility functions such as this is also a useful exercise for both beginning and accomplished programmers alike and can be a learning experience for the novices amongst us.编写像这样的小型实用函数对于初学者和有经验的程序员来说也是一个有用的练习,并且可以成为我们中间的新手的学习经验。

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"  */

Easily readable and customisable way to get a timestamp in your desired format, without use of any library:以您想要的格式获取时间戳的易于阅读和可定制的方式,无需使用任何库:

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())
}

(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth") (如果您需要 UTC 格式的时间,则只需更改函数调用。例如“getMonth”变为“getUTCMonth”)

The javascript library sugar.js ( http://sugarjs.com/ ) has functions to format dates javascript 库 Sugar.js ( http://sugarjs.com/ ) 具有格式化日期的功能

Example:例子:

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

Use the method provided in the Date object as follows:使用 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));

It looks really dirty, but it should work fine with JavaScript core methods它看起来很脏,但它应该适用于 JavaScript 核心方法

I am using dateformat at Nodejs and angularjs, so good我在 Nodejs 和 angularjs 上使用dateformat ,太好了

install安装

$ 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
...

Check the code below and the link to MDN检查下面的代码和指向MDN的链接

 // 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())

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

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

Alternative #6233....替代方案 #6233....

Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString() method of the Date object:将 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));

I'm creating a date object defaulting to the local time.我正在创建一个默认为本地时间的日期对象。 I'm adding the UTC off-set to it.我正在向它添加 UTC 偏移量。 I'm creating a date-formatting object.我正在创建一个日期格式对象。 I'm displaying the UTC date/time in the desired format:我以所需的格式显示 UTC 日期/时间:

在此处输入图片说明

For date formatting the most easy way is using moment lib.对于日期格式化,最简单的方法是使用 moment lib。 https://momentjs.com/ https://momentjs.com/

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

Use x-date module which is one of sub-modules of x-class library ;使用x-date模块,它是x-class的子模块之一;

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'

Here's a handy vanilla one-liner (adapted from this ):这是一个方便的香草单线(改编自this ):

 var timestamp = new Date((dt = new Date()).getTime() - dt.getTimezoneOffset() * 60000).toISOString().replace(/(.*)T(.*)\..*/,'$1 $2') console.log(timestamp)

Output: 2022-02-11 11:57:39 Output: 2022-02-11 11:57:39

I needed a simple formatting library without the bells and whistles of locale and language support.我需要一个简单的格式库,没有语言环境和语言支持的花里胡哨。 So I modified所以我修改了

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

and used it.并使用了它。 See https://github.com/adgang/atom-time/blob/master/lib/dateformat.jshttps://github.com/adgang/atom-time/blob/master/lib/dateformat.js

The documentation is pretty clear.文档很清楚。

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

with .toString(), This becomes in format使用 .toString(),这变成了格式

replace(/T/, ' ').替换(/T/,' ')。 //replace T to ' ' 2017-01-15T... //将 T 替换为 ' ' 2017-01-15T...

replace(/..+/, '') //for ...13:50:16.1271 replace(/..+/, '') //for ...13:50:16.1271

example, see var date and hour :例如,请参阅 var datehour

 var date="2017-01-15T13:50:16.1271".toString("yyyyMMddHHmmss"). replace(/T/, ' '). replace(/\\..+/, ''); var auxCopia=date.split(" "); date=auxCopia[0]; var hour=auxCopia[1]; console.log(date); console.log(hour);

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

Here's a lightweight library simple-date-format I've written, works both on node.js and in the browser这是我编写的一个轻量级库simple-date-format ,适用于 node.js 和浏览器

Install安装

  • Install with NPM使用 NPM 安装
npm install @riversun/simple-date-format

or或者

  • Load directly(for browser),直接加载(浏览器),
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format/lib/simple-date-format.js"></script>

Load Library加载库

  • ES6 ES6
import SimpleDateFormat from "@riversun/simple-date-format";
  • CommonJS (node.js) CommonJS (node.js)
const SimpleDateFormat = require('@riversun/simple-date-format');

Usage1用法1

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"

Run on Pen在笔上运行

Usage2用法2

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"

Patterns for formatting格式化模式

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

In reflect your time zone, you can use this为了反映您的时区,您可以使用它

 var datetime = new Date(); var dateString = new Date( datetime.getTime() - datetime.getTimezoneOffset() * 60000 ); var curr_time = dateString.toISOString().replace("T", " ").substr(0, 19); console.log(curr_time);

import dateFormat from 'dateformat';从“日期格式”导入日期格式; var ano = new Date() var ano = 新日期()

<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罗达佩

Modern web browsers (and Node.js) expose internationalization and time zone support via the Intl object which offers a Intl.DateTimeFormat.prototype.formatToParts() method.现代 web 浏览器(和 Node.js)通过提供Intl.DateTimeFormat.prototype.formatToParts()方法的 Intl object 公开国际化和时区支持。

You can do below with no added library:您可以在不添加库的情况下执行以下操作:

 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()));

You can use Light-Weight library Moment js您可以使用轻量级库Moment js

npm install moment

Call the library打电话给图书馆

var moments = require("moment");

Now convert into your required format现在转换成你需要的格式

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

And for more format and details, you can follow the official docs Moment js更多格式和细节,可以关注官方文档Moment js

I think this actually answers your question.我认为这实际上回答了你的问题。

It is so annoying working with date/time in javascript.在 javascript 中使用日期/时间非常烦人。 After a few gray hairs I figured out that is was actually pretty simple.几根白发后,我发现这实际上很简单。

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

Here is a fiddle这是一个小提琴

it's possible to solve this problem easily with '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}`;
}

it's to show: // 10/31/22 11:13:25它要显示:// 10/31/22 11:13:25

暂无
暂无

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

相关问题 如何使用javaScript将UTC日期时间转换为yyyy-mm-dd hh:mm:ss日期时间格式? - How to convert UTC date time into yyyy-mm-dd hh:mm:ss date time format using javaScript? 如何检查字符串是否为有效日期格式(格式应为:YYYY-MM-DD HH:mm:ss) - how to check the string is valid date format or not (format should be in : YYYY-MM-DD HH:mm:ss) 如何使用JavaScript将数据格式“ YYYY-mm-dd hh:mm:ss”转换为“ dd-mm-YYYY hh:mm:ss”? - How to convert data format “YYYY-mm-dd hh:mm:ss” to “dd-mm-YYYY hh:mm:ss” using javascript? yyyy-mm-dd HH:mm:ss 格式的 Javascript 日期现在 (UTC) - Javascript Date Now (UTC) in yyyy-mm-dd HH:mm:ss format Json字符串数组格式日期时间字段-yyyy-MM-dd hh:mm:ss - Json string array format Date Time field - yyyy-MM-dd hh:mm:ss 如何在 javascript 中解析 yyyy-MM-dd HH:mm:ss.SSS 格式的日期? - How to parse yyyy-MM-dd HH:mm:ss.SSS format date in javascript? 如何将“YYYY-MM-DD hh:mm:ss”格式的日期转换为 UNIX 时间戳 - How to convert date in format "YYYY-MM-DD hh:mm:ss" to UNIX timestamp 如何使用 Javascript 或 jQuery 从 YYYY-MM-DD HH:MM:SS 修剪 HH:MM:SS - How to trim HH:MM:SS from YYYY-MM-DD HH:MM:SS using Javascript or jQuery 如何将日期格式化为 (dd/mm/yyyy hh:mm:ss) - How to format the date to (dd/mm/yyyy hh:mm:ss) 从yyyy-mm-dd获取当前时间戳hh:mm:ss使用UTC / GMT + 0作为纪元 - Get current timestamp from yyyy-mm-dd hh:mm:ss using UTC/GMT+0 as epoch
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM