Below is the fixed date stored in an object, write a function that compares a date with the current date:
const docData = {
DateTransport: "2022-01-01",
TypeHeureDepart: "02:15",
};
I wrote the below solution but I think there may be a time zone problem?
const docData = {
DateTransport: "2022-01-01",
TypeHeureDepart: "02:15",
};
// true: past ; false: now or future
const docDataDate = new Date(2022, 0, 1, 2, 15, 0, 0);
const currentDate = new Date();
function checkTime() {
if (docDataDate >= currentDate) return false;
return true;
}
console.log(checkTime());
Above solution has some issues below:
a. I shouldn't assign variables outside of the function
b. I didn't use docData
c. The function is not reusable
d. there's no input in this function
// true: past ; false: now or future
const docData = {
DateTransport: "2022-01-01",
TypeHeureDepart: "02:15",
};
function checkTime(docData) {
const { DateTransport, TypeHeureDepart } = docData;
const docDataDate = new Date(
`${DateTransport} ${TypeHeureDepart || "00:00"}`
);
return new Date() > docDataDate;
}
console.log(checkTime(docData));
There are some important details:
- When compared with two date, it needs to be same format
1.1 if I use concat to connect the strings, it needs to be:
new Date(docData["DateTransport"] +'T'+docData["TypeHeureDepart"]+':00')
or
new Date(docData.DateTransport + "T" + docData.TypeHeureDepart + ":00")
1.2 use template literals: attention to the space or add a "T" in between them
const docDataDate = new Date(
`${DateTransport} ${TypeHeureDepart || "00:00"}`
);
Reference:
JavaScript Date Object Comparison
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
How to compare Date and Time in JavaScript - Step by Step
new Date(2022, 3, 15, 10, 22, 15)
//Fri Apr 15 2022 10:22:15 GMT+0800
The Date Object - Getting, Setting & Formatting Dates in JavaScript - Tutorial For Beginners