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

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

我怎么做呢?


当前回答

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(时光”);

其他回答

替代# 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日期/时间:

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

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

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

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

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

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

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

文档非常清楚。

从“日期格式”导入日期格式; 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