[英]JavaScript - Sort by Time String
I am not very good with manipulating strings and need some help. 我对操纵字符串不是很好,需要一些帮助。
I have this function which takes 2 divs and gets a paragraph that contains a string representing time in a format that looks like this: 我有这个函数,它需要2 divs,并获得一个段落,该段落包含一个表示时间的字符串,格式如下所示:
Friday, 7 August 2015, 18:21 PM 2015年8月7日,星期五,18:21 PM
or 要么
Tuesday, 21 August 2015, 10:45 AM 2015年8月21日,星期二,上午10:45
as 2 examples. 作为两个例子。 I want to create a sort comparator function which will return the correct number if one is larger than the other but I am not sure how to extract days when the number can be 1 or 2 digits long and also take into account the exact time etc..
我想创建一个排序比较器函数,如果一个大于另一个,它将返回正确的数字,但是我不确定如何提取数字可以为1或2位数字的天,并且还要考虑准确的时间等。 。
The time string is the innerText part which I have split where there is a comma so that atime and btime are arrays for each section. 时间字符串是innerText部分,在有逗号的地方我将其拆分,以便atime和btime是每个部分的数组。
Here is what I have done so far: 到目前为止,这是我所做的:
// format: Friday, 7 August 2015, 18:21 PM
// atime[0] --> Friday
// atime[1] --> 7 August 2015
// atime[2] --> 18:21 PM
function sortByTimeAdded(a, b) {
var atime = (a.getElementsByClassName('timeAdded')[0].innerText).split(',');
var btime = (b.getElementsByClassName('timeAdded')[0].innerText).split(',');
/*if (atime[1] < btime[1]) {
return -1;
}
if (atime[1] > btime[1]) {
return 1;
}*/
return 0;
}
Thank you! 谢谢!
I suggest using Date.parse , I will show on example: 我建议使用Date.parse ,我将在示例中显示:
var a = "Friday, 7 August 2015, 18:21 PM"
Date.parse(a.substring(0, a.length-3))
with this you get timestamp you can use for comparison. 通过此操作,您可以获得用于比较的时间戳记。
If you need date object just replace Date.parse with Date() 如果您需要日期对象,只需将Date.parse替换为Date()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.