[英]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兼容时间格式库的列表:
There are also non-Node libraries:还有非节点库:
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'
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.js
见https://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
date
和hour
:
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安装
npm install @riversun/simple-date-format
or或者
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format/lib/simple-date-format.js"></script>
Load Library加载库
import SimpleDateFormat from "@riversun/simple-date-format";
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"
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);
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);
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.