Having to dates like this
'2022-04-30' & '2022-05-30'
using javascript how can evaluate which dates is lower ?
I tried to convert them to milliseconds but with this format date I dont know how
example
if('2022-04-30' < '2022-05-30')
{
// true
}
EDIT: As pointed out by #RobG the dates are in the ISO format so there is no need for dates at all:
if ('2022-04-30' < '2022-05-30')
console.log('true')
However this does not work with other date formats, for example:
if ('30-04-2022' < '30-05-2020')
console.log('returns true, but is incorrect')
if (new Date('30-04-2022') < new Date('30-05-2020'))
console.log('returns false')
ORIGINAL ANSWER:
You are trying to compare strings not dates. Try this:
const date1 = new Date('2022-04-30');
const date2 = new Date('2022-05-30');
if (date1 < date2) {
console.log('true');
}
Or shorter:
if (new Date('2022-04-30') < new Date('2022-05-30'))
console.log('true');
Related
If I define a date range using purely date strings in yyyy-mm-dd format, it appears comparison will work just fine without using the Date object:
const dateParts = '2021-12-15--2022-01-15'.split('--') // My date range
const startDate = dateParts.slice(0, 1) // '2021-12-15'
const endDate = dateParts.slice(1) // '2022-01-15'
const date = '2021-12-14'
// Test if date is within the range
console.log(date >= startDate && date <= endDate) // false
Using any date in the above example will test successfully if what I want is ensure that the date I'm looking for is within the range.
Why is this working? If javascript was, under the hood, evaluating the date strings as numbers, this should not be working. Is it maybe just implicitly assuming it's a date without me having to parse them using new Date(date)...?
Update: I'm not looking for solutions on how to do this using the Date object, I'd be more interested in examples where comparing dates this way would NOT work.
Your code works (Or if it looks like its working) because its just a basic string comparison and not the date comparison. To do a proper date comparison, you need to do the proper string to date conversion, and then compare them.
const dateParts = '2021-12-15--2022-01-15'.split('--') // My date range
const startDate = dateParts[0] // '2021-12-15'
const endDate = dateParts[1] // '2022-01-15'
const startDateArray = startDate.split("-").map(element => parseInt(element));
const endDateArray = endDate.split("-").map(element => parseInt(element));
const date = '2022-01-15'
const dateArray = date.split("-").map(element => parseInt(element));
// Test if date is within the range
console.log(new Date(dateArray[0], dateArray[1] - 1, dateArray[2]) >= new Date(startDateArray[0], startDateArray[1] - 1, startDateArray[2]) && new Date(dateArray[0], dateArray[1] - 1, dateArray[2]) <= new Date(endDateArray[0], endDateArray[1] - 1, endDateArray[2])) // false
This should solve your problem
const dateParts = '2021-12-15--2022-01-15'.split('--'); // My date range
const startDate = dateParts[1]; // '2021-12-15'
const endDate = dateParts[0]; // '2022-01-15'
const date = '2021-12-10'
// Test if date is within the range
alert(date < startDate && date < endDate)
A really simple question. Are these two dates different:
2020-09-02T00:00:00.000+00:00 and 2020-09-02T15:39:00+04:00
I mean if I compare them will I get true or false.
The date I am retrieving from the backend (MongoDB) is 2020-09-02T00:00:00.000+00:00 and the one I am passing in the request body is 2020-09-02T15:39:00+04:00. The result I am getting is false when comparing.
If they are not the same, how do I convert this date 2020-09-02T15:39:00+04:00 into the DB format. I only want the dates to be checked not the time. TIA
You can parse the strings to Date objects and then compare the dateStrings.
toDateString returns the date portion of a Dateobject as a readable string.
const date1 = new Date("2020-09-02T00:00:00.000+00:00");
const date2 = new Date("2020-09-02T15:39:00+04:00");
function compareDates(date1, date2) {
return date1.toDateString() === date2.toDateString();
}
compareDates(date1, date2); //true
But since you're handling different timezones I would suggest to use other methods.
const date1 = new Date("2020-09-02T00:00:00.000+00:00");
const date2 = new Date("2020-09-02T15:39:00+04:00");
function compareDates(date1, date2) {
return date1.getUTCFullYear() === date2.getUTCFullYear() &&
date1.getUTCMonth() === date2.getUTCMonth() &&
date1.getUTCDate() === date2.getUTCDate();
}
compareDates(date1, date2); //true
the getUTC... methods return the year, month or day according to universal time.
I am trying to create an if statement that can check today's date and time and if it's greater than a predefined date and time, do something. I'm looking to do this in vanilla JS only and get it to work in IE.
This is the basic working code for Chrome.
var ToDate = new Date()
if (new Date("2018-11-30 05:00").getTime() > ToDate.getTime()) {
alert("true")
} else {
alert("false")
}
How can I make something like this work in IE?
if (new Date("2018-11-30 05:00").getTime() > ToDate.getTime()) {
On firefox and chrome there are no issues with it. On Internet Explorer it's false.
On IE (or in general) the string needs to be an RFC2822 or ISO 8601 formatted date
Example:
new Date("2018-11-29T19:15:00.000Z")
If you need portable solution (eg. support older Internet Explorer) I would use this constructor instead:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
Keep in mind that monthIndex starts from 0 (January).
Test:
function assertTrue(exp, message) {
if (exp === false) {
message = message || 'Assertion failed';
alert(message);
throw message;
}
}
function testShouldPassForDatesInTheFuture() {
var ToDate = new Date(2018, 10, 29);
assertTrue(new Date(2018, 10, 30).getTime() > ToDate.getTime());
}
function testShouldPassForDatesInThePast() {
var ToDate = new Date(2018, 10, 29);
assertTrue(new Date(2018, 10, 28).getTime() < ToDate.getTime());
}
testShouldPassForDatesInThePast();
testShouldPassForDatesInThePast();
alert('All test passed');
You need to append 'T00:00:00.000Z' to your date.
new Date("2018-11-30" + 'T00:00:00.000Z')
Full code is below:
var ToDate = new Date()
if (new Date("2018-11-30" + 'T00:00:00.000Z').getTime() > ToDate.getTime()) {
alert("true")
} else {
alert("false")
}
Your issue is that the date format YYYY-MM-DD HH:mm is not supported by ECMAScript, so parsing is implementation dependent. Safari, for example:
new Date("2018-11-30 05:00")
returns an invalid date.
You can first parse the string manually, either with a bespoke function (e.g. How to parse a string into a date object at JavaScript?) or a library, then you can compare the result with new Date() as for Compare two dates with JavaScript.
A simple parse function is not difficult:
/* Parse string in YYYY-MM-DD HH:mm:ss to a Date
* All parts after YYYY-MM are optional, milliseconds ignored
*/
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2]||1, b[3]||0, b[4]||0, b[5]||0);
}
["2018-11-23 17:23",
"2019-01",
"2020-12-31 23:59:59"].forEach(s => {
console.log(`${s} => ${parseDate(s).toString()}`);
});
Then you can compare dates using <, <=, > and >=.
In this case, a date like "2018-01-01" will be considered past at any time after 2018-01-01 00:00:00.000.
Alternatively, since the string is similar to ISO 8601 format, you can compare the parts of the string with a similarly formatted string for today:
// Return date string in YYYY-MM-DD HH:mm:ss format
// Only return as many parts as len, or all 6 if missing
function formatDate(d, len) {
var parts = [d.getFullYear(), '-'+d.getMonth()+1, '-'+d.getDate(), ' '+d.getHours(), ':'+d.getMinutes(), ':'+d.getSeconds()];
var spacer = ['-','-',' ',':',':'];
len = len || 6;
return parts.splice(0, len).join('');
}
['2018-06-30 12:04',
'2018-10',
'2018-12-15 03:14:45',
'2019-01-01',
'2020-12-15 03:14:45'].forEach(s => {
console.log(`${s} has passed? ${s < formatDate(new Date(), s.split(/\D/).length)}`);
});
In this case, 2018-01-01 will be equal to any date generated on that day, and "2018-01" will be equal to any date generated in January 2018. It's up to you whether you use < or <= for the comparison.
So you need to consider carefully where you draw the boundary between earlier and later and adjust the logic accordingly.
So I have a scenario where I need to compare Date1 and Date2
where Date1 = 05.01.2008 6:00 +5:00
and Date2 = 05.01.2008 7:00 +5:00
I am not getting a way to convert these datetimeoffsets to a particular conversion format. Plz help.
Here is what all i have tried till now
function validate()
{
var a = document.getElementById("txtDate1").innerHTML;
var b = document.getElementById("txtDate2").innerHTML;
if (a > b) {
alert('greater')
}
else {
alert('Smaller')
}
}
use below code. using Date.parse
var date1 = new Date(Date.parse("05.01.2008 6:00 +5:00"));
var date2 = new Date(Date.parse("05.01.2008 7:00 +5:00"));
if (date1 < date2) {
alert('Smaller')
} else if (date1 > date2) {
alert('greater')
} else {
alert("date1 === date2");
}
You would first need to parse them as Date objects for comparison. One popular option is using moment.js, since it can interpret many formats.
Then you can compare them by using Date.prototype.getTime function to get the Unix timestamp, which all use the same time zone.
The way you compare them at the moment is as String types, which will not work.
I want to check to see if a date is before today. If it is then I want to display the date but not the time, if it is today then I want to display the time and not the date. The date I am checking is in the dd-mm-yyy hh:mm format and so they do not compare.
Please see what I have below so far:
var created = '25-05-2012 02:15';
var now = new Date();
if (created < now) {
created_format = [ format the date to be 25-05-2012 ]
} else {
created_format = [ format the date to be 02:15 ]
}
I have tried using now.dateFormat() and now.format() after seeing these in other examples but I get "is not a function" error messages.
Start by getting the parts of your date string:
var created = '25-05-2012 02:15';
var bits = created.split(/[-\s:]/);
var now = new Date();
// Test if it's today
if (bits[0] == now.getDate() &&
bits[1] == (now.getMonth() + 1) &&
bits[2] == now.getFullYear() ) {
// date is today, show time
} else {
// date isn't today, show date
}
Of course there are other ways, but I think the above is the easiest. e.g.
var otherDate = new Date(bits[2], bits[1] - 1, bits[0]);
now.setHours(0,0,0,0);
if (otherDate < now) {
// otherDate is before today
} else {
// otherDate is not before today
}
Similarly, once you've converted the string to a date you can use getFullYear, getMonth, getDate to compare with each other, but that's essentially the same as the first approach.
You can use getTime method and get timestamp. Then you can compare it with current date timestamp.