繁体   English   中英

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"

我知道的方法是先使用parse将其转换为时间戳,然后再使用new 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对象识别,但我找不到在两者之间进行转换的简便方法。

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

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

替代(?)

 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> 

更新,错误的输出。 一种方法,使用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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM