且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript日期排序通过将字符串转换为日期格式

更新时间:2023-11-29 14:03:58

如果你把它放在一个字符串中,那就去做.

If you have this in a single string then do.

// first create an array by splitting the string at the newlines
var list = dateString.split('\n'); 
list = list
    .map( // for each element in the list (each date)
        function(val,idx){
            // use the first part(before the dot(.)), replace the - with spaces and convert to date
            return new Date(val.split('.')[0].replace(/-/g,' '));
    })
    .sort(); // at the end sort the results.

http://www.jsfiddle.net/gaby/rfGv8/

我们需要为每个日期()做的是

What we need to do for each date (line) is

2010-11-08 18:58:50.0_getCreated_10180(删除.之后的部分)
val.split('.')[0]

2010-11-08 18:58:50.0_getCreated_10180 (remove the part after the .)
accomplished with val.split('.')[0]

然后用空格替换 - 使其看起来像 2010 11 08 18:58:50,这是 Date 构造函数可接受的日期格式.
val.split('.')[0].replace(/-/g,' ')

then replace the - with a space to make it look like 2010 11 08 18:58:50 which is an acceptable date format for the Date constructor.
accomplished with val.split('.')[0].replace(/-/g,' ')

然后将其作为参数传递给Date的构造函数,创建一个Date对象
new Date(val.split('.')[0].replace(/-/g,' '))

Then pass it as a parameter to the constructor of Date to create a Date object
accomplished with new Date(val.split('.')[0].replace(/-/g,' '))

将上述方法应用于所有元素并获得一个新数组后,使用 .sort() 方法按升序对数组进行排序.

after applying the above to all elements and getting a new array use the .sort() method to sort the array in Ascending order.