javascript:将Unix转换为长日期格式的最短路径是什么?

时间:2018-05-14 12:22:02

标签: javascript ecmascript-6 ecmascript-5

我有一个ISO时间字符串:

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

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

"May 05, 2018"

我知道的方法是首先使用parse将其转换为时间戳,然后使用新的Date:

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对象识别,但我找不到在两者之间进行转换的简短方法。

3 个答案:

答案 0 :(得分:1)

您可以使用timestamptoString转换为所需格式并进行一些字符串操作:

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

答案 1 :(得分:0)

替代(?)

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+).*/, "$1,$2")
})
.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>

更新,错误的输出。一种方法,使用拆分重构:

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

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

答案 2 :(得分:-1)

您也可以使用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/

相关问题