在 JavaScript 中拆分日期字符串的更好方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29543783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:33:04  来源:igfitidea点击:

What is the better way to split Date string in JavaScript?

javascriptstringsplit

提问by DaniKR

I am getting from api xml data, where one of the xml elements is date time, which nodeValue is always in this format - string: "YYYY-MM-DD". (I can not request from api, to return me date time in diffrent format)

我从 api xml 数据中获取,其中 xml 元素之一是日期时间,其中 nodeValue 始终采用这种格式 - 字符串:“YYYY-MM-DD”。(我无法从 api 请求,以不同格式返回我的日期时间

My problem is to split and convert this format into this string: "DD.MM.YYYY"

我的问题是将此格式拆分并转换为以下字符串:“DD.MM.YYYY”

Basicly I did this:

基本上我是这样做的:

var myString = "2015-04-10"; //xml nodeValue from time element
var array = new Array();

//split string and store it into array
array = myString.split('-');

//from array concatenate into new date string format: "DD.MM.YYYY"
var newDate = (array[2] + "." + array[1] + "." + array[0]);

console.log(newDate);

Here is jsfiddle: http://jsfiddle.net/wyxvbywf/

这是 jsfiddle:http: //jsfiddle.net/wyxvbywf/

Now, this code works, but my question is: Is there a way to get same result in fewer steps?

现在,此代码有效,但我的问题是:有没有办法以更少的步骤获得相同的结果?

回答by KooiInc

should do the same

应该做同样的事情

var newDate = '2015-04-10'.split('-').reverse().join('.')
//                         ^          ^         ^ join to 10.04.2015
//                         |          |reverses (2 -> 0, 1 -> 1, 0 -> 2)
//                         | delivers Array

回答by nderscore

You could use a regular expression that has capture groups and use String.prototype.replaceto reformat it.

您可以使用具有捕获组的正则表达式并用于String.prototype.replace重新格式化它。

var newDate = myString.replace(/(\d{4})-(\d{2})-(\d{2})/, '..');

回答by Andy

Yes.

是的。

var newDate = '2015-04-10'.split('-').reverse().join('.');