简体   繁体   English

在 JavaScript 中更改格式日期

[英]Change format date in JavaScript

I want to change the format in JavaScript, to be Year-month-day I used this code to get 3 months before, but the format that was generated became like this 9/19/2019.我想在 JavaScript 中更改格式,为 Year-month-day 我使用此代码获得 3 个月前,但生成的格式变成了这样的 9/19/2019。 This my code:这是我的代码:

var d = new Date();
    d.setMonth(d.getMonth() - 3);
    var x = d.toLocaleDateString();
    console.log(x);

You can get Year, Month and Date and use string interpolation like below您可以获取年、月和日期并使用如下所示的字符串插值

 var d = new Date(); d.setMonth(d.getMonth() - 3); var formattedDate = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`; console.log(formattedDate);

You are using the toLocaleDateString() which will format to the result you received which is expected.您正在使用 toLocaleDateString() ,它将格式化为您收到的预期结果。

Reference Mozilla's Docs on Date() to get the right function for you there :)Date()上参考 Mozilla 的文档以获得适合您的功能:)

Most instances you are able to just piece it together yourself similar to:大多数情况下,您可以自己将其拼凑在一起,类似于:

const date = `${date.getYear()}/${date.getMonth()}/${date.getDay()}`;

It's not a nice solution but there are a lot of restrictions with OOTB Date()这不是一个很好的解决方案,但是 OOTB Date()有很多限制

为此,您可以使用momentjs ,这是一个轻量级且方便的库:

var d = moment(new Date()).subtract(3, 'months').format('dd-MMM-yyyy);
var x = d.toISOString().substring(0,10);
console.log(x);

//it will give you the format of y-m-d

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

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