简体   繁体   English

Javascript:将datetime转换为较短的格式?

[英]Javascript: convert datetime to shorter format?

I have a string of datetime that looks like this: 我有一串日期时间看起来像这样:

2017-04-17 18:26:03

I can use javascript to reformat and shorten it like so: 我可以使用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///

Now, I need to make it even shorter like this: 现在,我需要像这样使它更短:

17/04/17

Could someone please advice on this? 有人可以对此提出建议吗?

Any help would be appreciated. 任何帮助,将不胜感激。

EDIT: I don't want to use anything like moment.js or any other library as it is overkill. 编辑:我不想使用诸如moment.js或任何其他库之类的东西,因为它太过分了。

You're right, moment.js is overkill to do it. 没错,moment.js实在是太过分了。 But I'm not sure regex are the fastest way to do that and it isn't the most readable. 但是我不确定正则表达式是最快的方法,而且可读性也不强。 Moreover Date object has methods to do it. 此外,Date对象具有执行此操作的方法。 For example you can use toLocaleDateString() : 例如,您可以使用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"

And if you are concerned about performance, when formatting a lot of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property : 而且,如果您担心性能,则在格式化大量日期时,最好创建一个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"

If you're using a regex, you can just take the year modulo 100 when building the string: 如果您使用的是正则表达式,则在构建字符串时可以将年份取模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