JavaScript日期排序通过将字符串转换为日期格式 [英] Javascript date sorting by convert the string in to date format

查看:153
本文介绍了JavaScript日期排序通过将字符串转换为日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将这些字符串转换为日期格式并进行排序....请

How can i convert these strings in to date format and sort accordingly....please

2010-11-08 18:58:50.0_getCreated_10180  
2010-11-09 17:49:42.0_getCreated_10180  
2010-11-09 17:49:42.0_getCreated_10180  
2010-11-24 19:44:51.0_getCreated_10180  
2010-11-09 13:54:46.0_getCreated_10180  
2010-11-23 20:06:29.0_getCreated_10180  
2010-11-23 20:06:04.0_getCreated_10180  
2010-11-15 17:51:37.0_getCreated_10180 

提前感谢
Joseph

Thanks in advance, Joseph

推荐答案

如果你有一个字符串,那么你可以做。

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]然后将它作为参数传递给Date的构造函数来创建一个Date对象

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,' ')

br>
完成与新日期(val.split('。')[0] .replace(/ - / g,''))

在将所有元素应用到所有元素并获取新数组后,使用 .sort()方法对数组i进行排序n升序。

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

这篇关于JavaScript日期排序通过将字符串转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆