如何使用JavaScript比较日期字符串 [英] How to compare date string using javascript

查看:72
本文介绍了如何使用JavaScript比较日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下日期的字符串值 Sun Apr 07 2019 00:00:00 GMT-0300,并且我需要与以下日期格式2019-04-08T03:00:00.000Z 比较,请注意,两者都是同一天,我需要对它们进行比较并返回相等的天数

I have the following string value of a date, Sun Apr 07 2019 00:00:00 GMT-0300, and I need to compare with the following date format 2019-04-08T03:00:00.000Z, note that both are the same day, I need to compare them and return a true as being equal days,

但是我不知道如何使用javascript做到这一点,有帮助吗?

but I do not know how to do this using javascript, any help?

我试图做这样的事情,但它并没有使我成真:

I tried to do something like this but it does not return me true:

if (input) { 

     //input.value = "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)"

     var situation = angular.isArray(item.situation) ? item.situation : [item.situation]; 

     // situation = 
     //[
     //    0: "2019-04-08T03:00:00.000Z"
     //    1: "2019-04-13T03:00:00.000Z"
     //]

     if (!angular.isArray(input.value)) {
        condition = situation.indexOf(input.value) >= 0;

     } else if (angular.isArray(input.value)) {
        condition = $window._.intersection(situation, input.value).length > 0;
     }
}

if (condition) {
    break;
}

//input.value = "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)"

//input.value = "Sun Apr 07 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)"

 situation = 
     [
         0: "2019-04-08T03:00:00.000Z"
         1: "2019-04-13T03:00:00.000Z"
     ]

推荐答案

2019年4月7日星期日00:00:00 GMT-0300

Sun Apr 07 2019 00:00:00 GMT-0300

2019-04-08T03:00:00.000Z

2019-04-08T03:00:00.000Z

请注意,两者都是同一天

note that both are the same day

不,不是.

您可以将它们都转换为ISO字符串,而只是将它们的日期部分作为字符串进行比较(如果我正确地理解了这个问题,您只想比较日期而不需要时间):

You can convert them both to ISO string and just compare their date parts as strings (if I understood the question correctly, you want to compare date only, without time):

function isSameDate(date1, date2) {
  const [d1, ] = (new Date(date1)).toISOString().split('T');
  const [d2, ] = (new Date(date2)).toISOString().split('T');
  return d1 === d2;
}

这篇关于如何使用JavaScript比较日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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