10

所需的返回值应该是格式为 的字符串dd-mm-yyyy

我试图给 ISOString 一个格式日期 dd-mm-yyyy 并添加 GMT 但代码给了我这种格式。我能怎么做?

new Date().toISOString()
    .replace(/T/, ' ').      // replace T with a space
    .replace(/\..+/, '');     // delete the dot and everything after

'2012-11-04 14:55:45'

4

4 回答 4

13

我正在寻找 04-11-2012 日期格式

使用今天的日期(作为 ISO 字符串当前为“2016-03-08T13:51:13.382Z”),您可以执行以下操作:

new Date().toISOString().replace(/T.*/,'').split('-').reverse().join('-')

这个的输出是:

-> "08-03-2016"

这个:

  1. 抓住日期。
  2. 将其转换为 ISO 字符串。
  3. 替换 'T' 和它之后的所有内容。
  4. 通过拆分任何连字符 ('-') 将其转换为数组。( ["2016", "03", "08"])
  5. 反转数组的顺序。( ["08", "03", "2016"])
  6. 将数组作为字符串连接回来,用连字符分隔每个值。

这是一个使用您的日期 (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>

于 2016-03-08T13:52:54.010 回答
5

您可以使用new Date().toLocaleDateString("en-US");仅返回日期。今天回来"3/8/2016"了。

new Date().toLocaleDateString().replace(/\//g, '-');将其更改为带破折号的输出。这将在"3-8-2016"今天返回。

于 2016-03-08T14:03:28.450 回答
4

对于您的示例 '2012-11-04 14:55:45'

你可以这样做:new Date('2012-11-04 14:55:45').toISOString().split('T')[0]在一行中:)

于 2018-06-19T15:46:55.380 回答
1

您可以通过添加时区偏移量将本地日期转换为 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; }

于 2021-04-09T18:52:13.467 回答