Home > Back-end >  How to compare dates without including the hour
How to compare dates without including the hour

Time:02-22

So there is a column that has the date with the hour and i was trying to create a variable date with the same date, month, year and hour to be able to compare it wiht that date but this didn't work with me so I thought I would do that by creating the same date but when i compare i won't consider the hour but im facing some difficulties.

anyone of the two solutions would be great

I wrote many other codes but none of them worked and that was the last one i wrote

var date = new Date();
var year = date.getYear();
var month = date.getMonth()   1;  if(month.toString().length==1){var month = 
'0' month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0' day;}
var date = month '/' day '/' year;
Logger.log(date);

enter image description here

Im using java script in google app script.

Thank you!

CodePudding user response:

From MDN

We have a first step to create an object date.

let today = new Date()
let birthday = new Date('December 17, 1995 03:24:00')
let birthday = new Date('1995-12-17T03:24:00')
let birthday = new Date(1995, 11, 17)            // the month is 0-indexed
let birthday = new Date(1995, 11, 17, 3, 24, 0)
let birthday = new Date(628021800000)            // passing epoch timestamp

You can create your Date object following the example above that fits you better. I also recommend giving a good look into this page.

For the second step...

From there, you can use Date.now(). As explained here, this will return "A Number representing the milliseconds elapsed since the UNIX epoch."

The third step is... comparing both numbers. Which one is smaller will be an "earlier date" and vice-versa.

If some dates don't have time, I would consider it as midnight. Using the default Date format, that would be something like this.

yyyy-mm-ddThh:mm:ssZ

Ex:

2022-02-21T09:39:23Z

The Z at the end means UTC 0.

More about this on this link.

So, a date without time would be:

2022-02-21T00:00:23Z

  • Related