![](/img/trans.png)
[英]How to convert UTC date time into yyyy-mm-dd hh:mm:ss date time format using javaScript?
[英]How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?
使用 NodeJS,我想將Date
格式化為以下字符串格式:
var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");
我怎么做?
如果你使用 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(總是一件好事)。
更新 2021-10-06:添加了 Day.js 並刪除了@ashleedawg 的虛假編輯
更新 2021-04-07:@Tampa 添加了 Luxon。
更新 2021-02-28:現在應該注意 Moment.js 不再被積極開發。 它不會很快消失,因為它嵌入在許多其他事物中。 該網站有一些替代方案的建議以及原因的解釋。
更新 2017-03-29:添加了 date-fns,關於 Moment 和 Datejs 的一些注釋
2016 年 9 月 14 日更新:添加了 SugarJS,它似乎具有一些出色的日期/時間功能。
好的,因為沒有人真正提供過實際的答案,這里是我的。
圖書館無疑是以標准方式處理日期和時間的最佳選擇。 日期/時間計算中有很多邊緣情況,因此能夠將開發移交給庫很有用。
以下是主要的Node兼容時間格式庫的列表:
還有非節點庫:
有一個用於轉換的庫:
npm install dateformat
然后寫出你的需求:
var dateFormat = require('dateformat');
然后綁定值:
var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");
見日期格式
我一般不反對圖書館。 在這種情況下,通用庫似乎過大了,除非申請過程的其他部分過時。
編寫像這樣的小型實用函數對於初學者和有經驗的程序員來說也是一個有用的練習,並且可以成為我們中間的新手的學習經驗。
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" */
以您想要的格式獲取時間戳的易於閱讀和可定制的方式,無需使用任何庫:
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”)
javascript 庫 Sugar.js ( http://sugarjs.com/ ) 具有格式化日期的功能
例子:
Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')
使用 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 核心方法
我在 Nodejs 和 angularjs 上使用dateformat ,太好了
安裝
$ npm install dateformat
$ dateformat --help
演示
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
...
檢查下面的代碼和指向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
替代方案 #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')
使用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'
這是一個方便的香草單線(改編自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
我需要一個簡單的格式庫,沒有語言環境和語言支持的花里胡哨。 所以我修改了
http://www.mattkruse.com/javascript/date/date.js
並使用了它。 見https://github.com/adgang/atom-time/blob/master/lib/dateformat.js
文檔很清楚。
new Date().toString("yyyyMMddHHmmss").
replace(/T/, ' ').
replace(/\..+/, '')
使用 .toString(),這變成了格式
替換(/T/,' ')。 //將 T 替換為 ' ' 2017-01-15T...
replace(/..+/, '') //for ...13:50:16.1271
例如,請參閱 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;
}
這是我編寫的一個輕量級庫simple-date-format ,適用於 node.js 和瀏覽器
安裝
npm install @riversun/simple-date-format
或者
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format/lib/simple-date-format.js"></script>
加載庫
import SimpleDateFormat from "@riversun/simple-date-format";
const SimpleDateFormat = require('@riversun/simple-date-format');
用法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"
用法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"
格式化模式
https://github.com/riversun/simple-date-format#pattern-of-the-date
為了反映您的時區,您可以使用它
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);
從“日期格式”導入日期格式; 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>
現代 web 瀏覽器(和 Node.js)通過提供Intl.DateTimeFormat.prototype.formatToParts()
方法的 Intl object 公開國際化和時區支持。
您可以在不添加庫的情況下執行以下操作:
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()));
我認為這實際上回答了你的問題。
在 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 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.