簡體   English   中英

Javascript:將datetime轉換為較短的格式?

[英]Javascript: convert datetime to shorter format?

我有一串日期時間看起來像這樣:

2017-04-17 18:26:03

我可以使用javascript重新格式化並縮短它,如下所示:

var input = '2017-04-17 18:26:03';
var result = input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1');

console.log(result);

/////Prints This: 17/04/2017///

現在,我需要像這樣使它更短:

17/04/17

有人可以對此提出建議嗎?

任何幫助,將不勝感激。

編輯:我不想使用諸如moment.js或任何其他庫之類的東西,因為它太過分了。

沒錯,moment.js實在是太過分了。 但是我不確定正則表達式是最快的方法,而且可讀性也不強。 此外,Date對象具有執行此操作的方法。 例如,您可以使用toLocaleDateString()

const date = new Date('2017-04-17 18:26:03');

const formattedDate = date.toLocaleDateString("en-GB", {
    year: "2-digit",
    month: "numeric",
    day: "numeric"
});

console.log( formattedDate ); // "17/04/17"

而且,如果您擔心性能,則在格式化大量日期時,最好創建一個Intl.DateTimeFormat對象並使用其format屬性提供的功能:

const date = new Date('2017-04-17 18:26:03');

const dateFormatter = new Intl.DateTimeFormat("en-GB", {
    year: "2-digit",
    month: "numeric",
    day: "numeric"
});

const formattedDate = dateFormatter.format(date);

console.log( formattedDate ); // "17/04/17"

如果您使用的是正則表達式,則在構建字符串時可以將年份取模100。

let match = input.match(/^(\d+)-(\d+)-(\d+)\s+(\d+):(\d+):(\d+)$/)
let result = `${match[3]}/${match[2]}/${match[1] % 100}`
console.log(result)
//=> '17/4/17'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM