警报(dateObj)给出周三2009年12月30日00:00:00 GMT+0800

如何获得日期格式为2009/12/30?


当前回答

new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"

new Date().toLocaleString().split(',')[0]
"2/18/2016"

其他回答

为什么不使用方法toISOString()与切片或简单的toLocaleDateString()?

注意toISOString返回的时区总是零UTC偏移量,而在toLocaleDateString中它是用户代理的时区。

检查:

const d = new Date() //今天,现在 //时区0 UTC偏移量 console.log (d.toISOString()。slice(0, 10)) // YYYY-MM-DD //用户代理的时区 console.log(d.toLocaleDateString('en-CA')) // YYYY-MM-DD .log(d.toLocaleDateString('en-CA') console.log(d.toLocaleDateString('en-US')) // M/D/YYYY .log(d.toLocaleDateString('en-US') console.log(d.toLocaleDateString('de-DE')) // d.m.y yyyy .log console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY .log(d.toLocaleDateString('pt-PT')

var dt = new Date();

dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();

因为月份索引是以0为基础的,所以必须加1。

Edit

有关日期对象函数的完整列表,请参见

Date

getMonth()

根据当地时间返回指定日期中的月份(0-11)。

getUTCMonth()

根据世界时返回指定日期中的月份(0-11)。

2021的答案

你可以使用本地的. tolocaledatestring()函数,它支持一些有用的参数,如区域设置(选择MM/DD/YYYY或YYYY/MM/DD格式),时区(转换日期)和格式详细选项(例如:1 vs 01 vs一月)。

例子

new Date().toLocaleDateString() // 8/19/2020

new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)

new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale

new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale

new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)

new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"});  // 09 (just the hour)

注意,有时要以特定的格式输出日期,必须找到与该格式兼容的区域设置。 您可以在这里找到本地示例:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

请注意locale只是改变格式,如果你想将特定日期转换为特定国家或城市的等效时间,那么你需要使用timezone参数。

您可以简单地使用这一行代码以年-月-日格式获取日期

var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
var date = new Date().toLocaleDateString()
"12/30/2009"