简体   繁体   中英

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

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 )

My problem is to split and convert this format into this string: "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/

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

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

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

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

是。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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