简体   繁体   English

日期在 Node.js 中失去前导 0

[英]Date loses leading 0's in Node.js

I need a string with current date and time in the following format:我需要一个具有以下格式的当前日期和时间的字符串:

"2021-06-02 09:37:38" “2021-06-02 09:37:38”

 const today = `${new Date().toLocaleDateString('sv-se')} ${new Date().toLocaleTimeString('sv-se')}`; console.log(today);

This code runs fine in any browser console I've tried, but if I run this in Node.js the leading 0's are gone in the date part (not the time part):此代码在我尝试过的任何浏览器控制台中运行良好,但如果我在 Node.js 中运行此代码,则日期部分(而不是时间部分)中的前导 0 消失了:

"2021-6-2 09:37:38" “2021-6-2 09:37:38”

Is there a nice way to fix this without splitting and padding?有没有一种很好的方法来解决这个问题而无需拆分和填充?

I would prefer to avoid installing any dependencies.我宁愿避免安装任何依赖项。

EDIT: Node version is v11.15.0.编辑:节点版本是 v11.15.0。

You should try to add options as a 2nd parameter to toLocaleDateString .您应该尝试将选项作为第二个参数添加到toLocaleDateString For example try this: var options = {year: "numeric", month: "2-digit", day: "2-digit"};例如试试这个: var options = {year: "numeric", month: "2-digit", day: "2-digit"};

If this does not fit your needs exactly refer to https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString如果这不符合您的需求,请参阅https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM