javascript: Unix转长日期格式最短的方法是什么

javascript: What is the shortest way to convert Unix to long date format

我有一个 ISO 时间字符串:

"2018-05-14T14:04:53.16"

我需要将其转换为以下内容:

"May 05, 2018"

我知道的方法是先使用解析将其转换为时间戳,然后是新日期:

let timestamp = new Date(Date.parse("2018-05-14T14:04:53.16"))

然后分别获取每个部分,将它们映射到映射数组,然后连接它们:

let monthNames = ['January','Fabruary'...];
let month = timestamp.getMonth(); //gatDay/getYear
let monthName = monthNames[month - 1] 

然后最终将所有部分连接成一个字符串:

let finalString = monthName+' '+day+', '+year;

有没有更短的方法来做到这一点? 我问是因为 javascript Date 对象可以识别这两种日期格式,但我找不到在两者之间进行转换的捷径。

您可以使用 toString 和一些字符串操作将 timestamp 转换为所需的格式:

timestamp.toString().replace(/\w+ (\w+ \d+)( \d+).*/, ",")

另类(?)

console.log(
new Date("2018-05-14T14:04:53.16").toUTCString().substr(0,12)
)

性能测试!(使用benchmark.js

var suite = new Benchmark.Suite;

// add tests
suite.add('toUTCString().substr', function() {
  new Date("2018-05-14T14:04:53.16").toUTCString().substr(0,12)
})
.add('Regex', function() {
  timestamp = new Date(Date.parse("2018-05-14T14:04:53.16"))
  timestamp.toString().replace(/\w+ (\w+ \d+)( \d+).*/, ",")
})
.add('toUTCString().split', function() {
  var d = new Date("2018-05-14T14:04:53.16").toUTCString().split(" ");
    d[2] +  ", " + d[1] + " " +d[3]
})
// add listeners
.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/2.1.4/benchmark.min.js"></script>

更新,输出错误。一种方法,使用 split 重组:

var d = new Date("2018-05-14T14:04:53.16").toUTCString().split(" ")

console.log(
d[2] +  " " + d[1] + ", " +d[3]
)

您也可以使用 moment.js:

var newDate = new moment("2018-05-14T14:04:53.16");
var html = 'Result: <br/>';
html += 'Formatted: ' + newDate.format('MMM DD, YYYY');

$('#output').html(html);

JSFiddle:https://jsfiddle.net/okd4mdcw/