简体   繁体   English

排序日期字符串javascript

[英]Sort date strings javascript

I have datetimes and dates stored as strings in javscript that I need to compare. 我有需要比较的日期时间和日期作为字符串存储在javscript中。

Leaving them as strings seems to work: 将它们保留为字符串似乎可行:

const date1 = '2016-01-26 05:20:44'
const date2 = '2016-01-26 06:20:44'
const date3 = '2016-02-26'

date1 > date2 //false
date1 < date2 //true
date3 > date2 //true
date3 > date1 //true
date1 > date3 //false

The question: can I depend on this? 问题:我可以依靠吗? Or is this a "it works, but it's not reliable" kind of deal? 还是这是一种“有效但不可靠”的交易?

Should I convert the date strings into date objects (using date or moment ) 我应该将日期字符串转换为日期对象(使用datemoment

If that is your format, it should continue to work. 如果那是您的格式,它应该继续工作。 Think about it: one of the major advantages of that format is exactly that it's sortable. 想一想:这种格式的主要优点之一就是它可以排序。

Of course Date objects themselves are also sortable. 当然,Date对象本身也是可排序的。 The internal valueOf method used in comparing them returns milliseconds since a fixed time. 用于比较它们的内部valueOf方法返回自固定时间以来的毫秒数。

Updated..... 更新.....

function removeAllNoNumber(a) {
   return  a.toString().replace(/\D/g, '');
}

function padRight(source, padChar, padCount) {
  var dif = padCount - source.toString().length;
  if (dif <= 0) {
     return source;
  } else {
     var c = "";
     for (var i = 0; i < dif; i++) {
         c += padChar.toString();
     }
         return (source + c);
     }
}

function timeToInt(a){
     return parseInt(padRight(removeAllNoNumber(a),"0",14),10);
}


  var date1 = timeToInt("2016-01-26 05:20:44"); //20160126052044 
  var date2 = timeToInt("2016-01-26 06:20:44"); //20160126062044
  var date3 = timeToInt("2016-01-26"); //20160126000000

   if (date1 < date2) {

     alert("here");
   }

Like this you can take extract the date from your given strings in the problem if the format never changes by using substring() 这样,如果格式从未更改,则可以使用substring()从问题中给定的字符串中提取日期。

date1.substring(0,10)
date2.substring(0,10)
date3.substring(0,10)

output to substring 输出到子字符串

"2016-01-26"

"2016-01-26"

"2016-02-26"

and now you can compare the extracted substrings of dates by comparing them like 现在,您可以通过比较日期来比较提取的日期子字符串,例如

date1.substring(0,10) > date1.substring(0,10) //false

It is little messy but it will keep you main string unchanged. 有点混乱,但是它将使您的主字符串保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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