如何比较两个给定的日期字符串?

时间:2019-02-08 20:50:06

标签: javascript string

我有两个给定的字符串值,例如

var A = '2019/2/8 23:59:59';
var B = '2019/2/10 23:59:59';

if (A > B) {
  console.log("A id Bigger Than B");
} else {
  console.log("B id Bigger Than A");
}

如何比较它们以找到最大的数据?

var A = '2019/2/8 23:59:59';
var B = '2019/2/10 23:59:59';

if (A > B) {
  console.log("A id Bigger Than B");
} else {
  console.log("B id Bigger Than A");
}

1 个答案:

答案 0 :(得分:1)

对日期进行归一化,字符串比较可以正常工作,而不会浪费创建日期对象的时间

var A = '2019/2/8 23:59:59',
    B = '2019/2/10 23:59:59',
    re = /\b(\d{1})\b/g;

A = A.replace(re,'0$1');
B = B.replace(re,'0$1');

console.log(A,B)

console.log("A is "+(A > B ? "later":"earlier")+ " than B");