Tam*_*mpa 218 javascript date node.js
使用NodeJS,我想将a格式化Date为以下字符串格式:
var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");
我怎么做?
chb*_*own 472
如果你正在使用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(总是一件好事).
Jul*_*ght 101
更新2017-03-29:添加日期fns,关于Moment和Datejs的一些注释
更新2016-09-14:添加了SugarJS,它似乎有一些出色的日期/时间功能.
好的,既然没有人真正提供过实际答案,这就是我的.
图书馆当然是以标准方式处理日期和时间的最佳选择.在日期/时间计算中有许多边缘情况,因此能够将开发移交给库是有用的.
以下是主节点兼容时间格式库的列表:
还有非节点库:
Ond*_*CAN 62
有一个转换库:
npm install dateformat
然后写下你的要求:
var dateFormat = require('dateformat');
然后绑定值:
var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");
HBP*_*HBP 40
我一般都不反对图书馆.在这种情况下,通用库似乎过度,除非应用程序的其他部分过程严重.
编写诸如此类的小实用功能对于初学者和有成就的程序员来说也是一种有用的练习,对于我们中的新手来说可以是一种学习体验.
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"  */
Mtl*_*Dev 10
易于阅读和自定义的方式来获得所需格式的时间戳,而无需使用任何库:
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}')
我在 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
...
对于日期格式化,最简单的方法是使用 moment lib。https://momentjs.com/
const moment = require('moment')
const current = moment().utc().format('Y-M-D H:M:S')
替代#6233....
将 UTC 偏移量添加到本地时间,然后使用toLocaleDateString()该对象的方法将其转换为所需的格式Date:
// 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 日期/时间:
使用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核心方法配合使用
检查下面的代码和指向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())| 归档时间: | 
 | 
| 查看次数: | 404193 次 | 
| 最近记录: |