所需的返回值应为格式为new Date().toISOString()
.replace(/T/, ' '). // replace T with a space
.replace(/\..+/, ''); // delete the dot and everything after
的字符串。
我试图给ISOString一个格式日期dd-mm-yyyy并添加GMT,但代码给了我这种格式。我该怎么办?
{{1}}
' 2012-11-04 14:55:45'
答案 0 :(得分:7)
我正在寻找04-11-2012日期格式
使用今天的日期(作为ISO字符串目前为“2016-03-08T13:51:13.382Z”),您可以这样做:
new Date().toISOString().replace(/T.*/,'').split('-').reverse().join('-')
这个输出是:
-> "08-03-2016"
此:
["2016", "03", "08"]
)["08", "03", "2016"]
)以下是使用您的日期(2012-11-04T14:55:45.000Z)作为输入的演示:
var input = "2012-11-04T14:55:45.000Z",
output;
output = new Date(input).toISOString().replace(/T.*/,'').split('-').reverse().join('-');
document.getElementById('input').innerHTML = input;
document.getElementById('output').innerHTML = output;
<p><strong>Input:</strong> <span id=input></span></p>
<p><strong>Output:</strong> <span id=output></span></p>
答案 1 :(得分:0)
您可以使用new Date().toLocaleDateString("en-US");
仅返回日期。这会在今天返回"3/8/2016"
。
new Date().toLocaleDateString().replace(/\//g, '-');
会将其更改为带破折号的输出。这将在今天返回"3-8-2016"
。
答案 2 :(得分:0)
例如您的'2012-11-04 14:55:45'
您可以执行以下操作:new Date('2012-11-04 14:55:45').toISOString().split('T')[0]
一行:)
答案 3 :(得分:0)
您可以通过添加时区偏移量将本地日期转换为 UTC 日期,然后调用 toLocaleDateString
(英式格式),同时用破折号替换斜杠并删除逗号。
// Adapted from: https://stackoverflow.com/a/55571869/1762224
const toLocaleUTCDateString = (date, locales, options) =>
new Date(date.valueOf() + (date.getTimezoneOffset() * 6e4))
.toLocaleDateString(locales, options);
// 'en-GB' === 'dd/mm/yyyy'
const formatDate = date =>
toLocaleUTCDateString(date, 'en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
.replace(/\//g, '-').replace(/,/, '');
const date = new Date();
console.log({
'ISO-8601': date.toISOString(),
'Custom': formatDate(date)
});
.as-console-wrapper { top: 0; max-height: 100% !important; }
或者,您可以尝试解析 ISO 8601 字符串:
const formatDate = _date =>
(([year, month, date, hour, minute, second, milliseconds]) =>
`${date}-${month}-${year} ${hour}:${minute}:${second}`)
(_date.toISOString().split(/[^\d]/g));
const date = new Date();
console.log({
'ISO-8601': date.toISOString(),
'Custom': formatDate(date)
});
.as-console-wrapper { top: 0; max-height: 100% !important; }