Comparing dates in javascript doesn't always work [duplicate] - javascript

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 6 years ago.
I am trying to compare two dates to see if one date is less than the other date, so I format both dates, then check if the expiry date is less than today and if it then show an alert message:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
var ExpiryDate = result.VATExpiryDate;
var day = ExpiryDate.getDate();
var month = ExpiryDate.getMonth()+1;
var year = ExpiryDate.getFullYear();
if(day<10){
day='0'+day
}
if(month<10){
month='0'+month
}
var ExpiryDate = day+'/'+month+'/'+year;
if(ExpiryDate < today && result.VATAuthNo.length>0)
{
alert("Please note Vat Authorisation Date for " + result.Name + " has expired - " + ExpiryDate);
}
But it seems it doesn't work for all dates. For example if the expiry date is 10/12/2015 it works and the alert message shows. But if the date is 21/06/2016 it doesn't work, even though that date is less than today.

You can compare dates operating directly with date object, not need to convert. javascript is a powerful language mate.
var today = new Date();
var expDate = new Date(2016, 10, 02)
if (today > expDate)
alert("expired");

Use the following method:
if( new Date(first).getTime() > new Date(second).getTime() ) {
// code;
}
var date1 = new Date('2017-02-15');
var date2 = new Date('2017-02-15');
if( date1 === date2 ){
console.log("bot are equal");
}
if( +date1 === +date2 ){
console.log("bot are equal");
}

You are comparing strings - to have correct results you shoud use format like YYYY-mm-dd not dd/mm/YYYY

Related

How to compare today date with another date in javascript? [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
I am trying to compare old date with today's date but I am not getting output true. Please help me.
let today = new Date(); // 2021-02-13T13:28:28.501Z
if ("2020-11-04T08:01:25.698Z" < today){
console.log("True");
}
Variable today is a date object you need to compare it with date object only and then only you will get the desired results
if (new Date() === today ) console.log('true')```
You can compare two dates (Date objects) using getTime method
console.log(date1.getTime() > date2.getTime())
This example prints true if date1 is later than date2
In your case:
let today = new Date();
let otherDay = new Date("2020-11-04T08:01:25.698Z");
if (otherDay.getTime() < today.getTime()){
console.log("True");
}
You need to convert string to date first
if (new Date("2020-11-04T08:01:25.698Z") < today){
console.log("True");
}
let today = new Date(); // 2021-02-13T13:28:28.501Z
if (new Date("2020-11-04T08:01:25.698Z") < today)
{
console.log("True");
}
Convert string to Date object and compare.
you can create an isTodaySameDay function and call it.
check out the snippet code below:
const isTodaySameDay = (day) => {
const today = new Date();
return day.getFullYear() === today.getFullYear() &&
day.getMonth() === today.getMonth() &&
day.getDate() === today.getDate();
};
let yesterday = new Date();
yesterday.setDate(yesterday .getDate() - 1);
console.log(isTodaySameDay(yesterday)); //false
let today = new Date();
console.log(isTodaySameDay(today)); //true

Why is my date comparison not working in JavaScript? [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 6 years ago.
I have pretty extensively researched this issue, and I've found some useful information, but I haven't been able to solve my problem. All I'm trying to do is parse a date and compare it to another date. Seems simple, right? Here is what I've tried:
function getCurrentDate() { //this function simply returns today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
return today;
}
$("#TxtDate").blur(function () {
var projectDueDate = Date.parse($("#lblDueDate").val()); //parses the project due date label to create a date variable
var itemDueDate = new Date($("#TxtDate").val()); //parses the value the user entered into the due date box to create a date variable
var actualProjectDueDate = new Date(projectDueDate);
if (Date.parse(document.getElementById('TxtDate').value) > getCurrentDate()) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtDate").val() = "";
}
});
The if statement isn't working in the TxtDate blur function. It is not showing the alert window, even though I am entering a date that precedes today's date. As you can see, I've tried some different things. Any suggestions?
Your function getCurrentDate is returning a string not a date object and you are comparing it with date object. So you need to parse the return value of getCurrentDate.
if (Date.parse(document.getElementById('TxtDate').value) > Date.parse( getCurrentDate())) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtLeaveFrom").val() = "";
}
Date.parse() returns a date object while getCurrentDate() returns a string. Add the Date.parse() there too:
if (Date.parse(document.getElementById('TxtDate').value) > Date.parse(getCurrentDate()))

Comparing datetimes in javascript in format YYYY-MM-DD HH:MM:SS

I have to compare two date times in javascript. The dates I have are of the form
YYYY-MM-DD HH:MM:SS.
I am using the below code for it
var date1 = new Date("2015-08-20 09:38:20");
var date2 = new Date("2015-08-20 08:00:00");
The problem here is that when I use "/" in place of "-", I get the expected results. But when for this format I do
date1 > date
It returns false
Using momentJs is not an option for me and also I am getting the dates from soemewhere so would have to preserve the format. How do I compare the dates of the above given format in javascript
Try this:
var date1 = '2015-08-20 09:38:20';
var date2 = '2015-08-20 08:00:00';
var date1Updated = new Date(date1.replace(/-/g,'/'));
var date2Updated = new Date(date2.replace(/-/g,'/'));
console.log(date1Updated > date2Updated);
I was not able to reproduce the given behavior, but you could try
converting the date1 and date2 variables to miliseconds and storing those in separate vars since Jan 1st 1970.
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
this gives ( for your given example )
1440056300000
1440050400000
and in a comparison
date1_ms > date2_ms
returns true
This is typical of JavaScript dates. All browsers seem to treat date strings differently. My experience is write your own parser if you know the format you want to deal with.
Something like the below will work. Feel free to tidy it up and make it more generic for your own use.
function parseDateString(dateString) {
var dateParts = dateString.split(' ');
var dateOnlyString = dateParts[0];
var timeString = dateParts[1];
var dateOnlyParts = dateOnlyString.split('-');
var year = dateOnlyParts[0];
var month = dateOnlyParts[1] - 1;
var day = dateOnlyParts[2];
var timeParts = timeString.split(':');
var hours = timeParts[0];
var minutes = timeParts[1];
var seconds = timeParts[2];
return new Date(year, month, day, hours, minutes, seconds);
}
jsfiddle for test: http://jsfiddle.net/04nh4q9w/
function getDate(dateString) {
//This function assumes that the dateString will always be of the format YYYY-MM-DD HH:MM:SS
var dateParts = dateString.split(' ');
var dateStr = dateParts[0].split('-');
var timeStr = dateParts[1].split(':');
var dateTimeArr = datestr.concat(timestr)
return new Date(dateTimeArr[0], dateTimeArr[1]-1, dateTimeArr[2], dateTimeArr[3], dateTimeArr[4], dateTimeArr[5]);
}
var date1 = getDate("2015-08-20 09:38:20");
var date2 = getDate("2015-08-20 08:00:00");
date1 > date2 will be true for any browser.
function convertTo24Hour(time) {
time = time.toUpperCase();
var hours = parseInt(time.substr(0, 2));
if(time.indexOf('AM') != -1 && hours == 12) {
time = time.replace('12', '0');
}
if(time.indexOf('PM') != -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
return time.replace(/(AM|PM)/, '');
}

compare string with today's date in JavaScript

I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>

Check if a date within in range

I am trying to check if a date of format mm.dd.yyyy is greater than today and less than the date after 6 months from today.
Here is my code:
var isLinkExpiryDateWithinRange = function(value) {
var monthfield = value.split('.')[0];
var dayfield = value.split('.')[1];
var yearfield = value.split('.')[2];
var inputDate = new Date(yearfield, monthfield - 1, dayfield);
var today = new Date();
today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
alert(inputDate > today);//alert-> true
var endDate = today;
endDate.setMonth(endDate.getMonth() + 6);
alert(inputDate > today);//alert-> false
if(inputDate > today && inputDate < endDate) {
alert('1');
} else {
alert('2');/always alert it
}
}
If I execute isLinkExpiryDateWithinRange('12.08.2012') I wish it will show 1 as this is within the range, but it is displaying 2. Moreover the first alert is showing true and the second one false.
Can anyone please explain what is happening?
Change:
var endDate = today;
to:
var endDate = new Date(today);
See the posts here for how objects are referenced and changed. There are some really good examples that help explain the issue, notably:
Instead, the situation is that the item passed in is passed by value.
But the item that is passed by value is itself a reference.
JSFiddle example
function isLinkExpiryDateWithinRange( value ) {
// format: mm.dd.yyyy;
value = value.split(".");
var todayDate = new Date(),
endDate = new Date( todayDate.getFullYear(), todayDate.getMonth() + 6, todayDate.getDate() +1 );
date = new Date(value[2], value[0]-1, value[1]);
return todayDate < date && date < endDate;
}
isLinkExpiryDateWithinRange("12.24.2012"); // true
isLinkExpiryDateWithinRange("12.24.2020"); // false
Below function checks if date selected is within 5 days from today. Date format used is "DD-MM-YYYY", you can use any format by changing value.split('-')[1] order and split character.
function showMessage() {
var value = document.getElementById("invoiceDueDate").value;
var inputDate = new Date(value.split('-')[2], value.split('-')[1] - 1, value.split('-')[0]);
var endDate = new Date();
endDate.setDate(endDate.getDate() + 5);// adding 5 days from today
if(inputDate < endDate) {
alert("If the due date selected for the invoice is within 5 days, and express settlement fee will apply to this transaction.");
}
}

Categories

Resources