0

I want to get the difference between days, but there is time and other information attached with this date format. 2021-04-05T19:12:33.000Z

How do we eliminate all the other time and just get the year, month, day fields to find the difference between days?

AKA How do you convert 2021-04-05T19:12:33.000Z

to

just the year, month day and no seconds? 2021-04-05T00:00:00.000Z

or just get

2021-04-05? Or any other format to get the difference between 2 days and not considering the timestamps?

I'm thinking of extracting the year, month and day from the string and set it as fields. Then pass it into

const year = ("2021-04-05T19:12:33.000Z").substring(0,4)
const month .. etc

new Date('05/04/2021') manually, but is there a better way to extract month, day, year from 2021-04-05T19:12:33.000Z ? Then find the days difference?

Thank you!

Suzy
  • 231
  • 4
  • 14
  • You can subtract the date objects from each other and divide the result by `24 * 3600 * 1000`. Now round down (or up) to get an integer. –  May 21 '21 at 21:28

1 Answers1

0

To extract the different portions, just parse the date:

const dt = new Date("2021-04-05T19:12:33.000Z")

console.log(dt.getFullYear())
console.log(dt.getMonth() + 1) // js is stupid and 0 indexes the month
console.log(dt.getDate())

To find the number of days between two dates, though,

const dt1 = new Date("2021-04-05T19:12:33.000Z")
const dt2 = new Date("2021-04-11T19:12:33.000Z")

dt1.setHours(0);
dt1.setMinutes(0);
dt1.setSeconds(0);
dt1.setMilliseconds(0);
dt2.setHours(0);
dt2.setMinutes(0);
dt2.setSeconds(0);
dt2.setMilliseconds(0);

console.log((dt2 - dt1) / (24 /* hours */ * 60 /* minutes */ * 60 /* seconds */ * 1000 /* milliseconds */))
dave
  • 62,300
  • 5
  • 72
  • 93
  • This is a dupe: https://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript –  May 21 '21 at 21:37
  • Great thanks Dave! I think it's different than the attached link since this is resetting items to 0 and using get dates instead of string manipulation – Suzy May 22 '21 at 05:22
  • "2021-04-05T19:12:33.000Z" is parsed as UTC, *setHours* etc. set the local time. All time parts can be done in one call: `dt1.setHours(0,0,0,0)`. The result will not be an integer number of days where daylight saving is observed and the date range crosses a DST boundary. – RobG May 22 '21 at 08:57