Check the dates in JavaScript - javascript

I want to check two dates in java script. date format is YYYY-MM-dd.
var date1 = 2011-9-2;
var date1 = 2011-17-06;
Can anybody say how can I write condition?

If you mean that you want to compare them and your variables are strings, just use == for comparison.
var date1 = '1990-26-01';
var date2 = '2000-01-05';
if (date1 == date2) {
alert('date1 = date2')
}
else {
alert('something went wrong');
}

There are four ways of instantiating dates
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Here is the link to complete tutorial and function of creating, comparing dates http://www.w3schools.com/js/js_obj_date.asp

If you want to compare dates , have a look at the JS date object https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date , in particular the getTime() method .

Assuming the format is YYYY-MM-dd (your second date value breaks this rule) and that they are strings...
var date1 = '2011-9-2';
var date2 = '2011-06-17';
var fields = date1.split("-");
var d1 = new Date (fields[0], fields[1]-1, fields[2]);
var fields = date2.split("-");
var d2 = new Date (fields[0], fields[1]-1, fields[2]);

Related

JavaScript - Get array of dates between start and end dates

I got this code (off GitHub) It does exactly what I want except the months produced are a month ahead of the months in the JavaScript code. The months in this code are 02 (February) but the months produced on screen are 03 (March). What am I not seeing here? Is it the way the dates are written?
<script>
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate,1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2021,02,22), new Date(2021,02,27));
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
</script>
As Timespider pointed out, getDates function is OK. You mus be careful when creating a new Date value, since months go from 0 to 11 in the Date constructor function:
// Usage
var fromFeb22 = new Date(2021,1,22);
var toFeb27 = new Date(2021,1,27);
var dates = getDates(fromFeb22 , toFeb27 );
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
UPDATE: Using with jQuery's DatePicker
The jQuery's DatePicker widget has a getDate method which returns a Date object that you can use directly in your function (no need to use new Date()):
// Usage
var fromDate = $("#fromDate").datepicker("getDate");
var toDate = $("#toDate").datepicker("getDate");
var dates = getDates(fromDate, toDate);
dates.forEach(function(date) {
document.write(date);
console.log(date);
});
Using with standard date input <input type="date"/>
The standard date input returns the date as a string formatted like "yyyy-MM-dd", but it is easy to parse it into a Date object:
// Usage
var fromDate = new Date(document.querySelector("#fromDate").value);
var toDate = new Date(document.querySelector("#toDate").value);
var dates = getDates(fromDate, toDate);
dates.forEach(function(date) {
document.write(date);
console.log(date);
});

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>

Convert Returned String (YYYYMMDD) to Date

I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

Javascript validation of date select boxes

I have created 3 select boxes containing days, months and year. What I really would like is to check after the user has selected a date, if the date is over a year from the current date a message is displayed or so.
Im a little stumped on what to do. Any gidance would be great.
Thanks
var ddlYear = document.getElementById('ddlYear');
var ddlMonth = document.getElementById('ddlMonth');
var ddlDay = document.getElementById('ddlDay');
var y = ddlYear[ddlYear.selectedIndex];
var m = ddlMonth[ddlMonth.selectedIndex];
var d = ddlDay[ddlDay.selectedIndex];
// past
var dt = new Date((y+1), (m-1), d);
var moreThanOnYearAgo = dt < new Date();
// future
var dt2 = new Date((y-1), (m-1), d);
var moreThanOnYearAhead = dt2 > new Date();
The y+1 is because if we're adding one year, and are still less than new Date() (today), then it's more than one year ago.
The m-1 is because months in the Date constructor are an enum, which means January is 0.
Don't reinvent the wheel one more time. Use a library that does validation.
There are 31556926000 milliseconds in a year. Just convert that date to a timestamp and subrtact the current date from it. If the result is greater than 31556926000 from it, is over a year away.
var userDate = new Date("11/29/2010");
var now = new Date();
var year_ms = 31556926000;
if ( userDate.getTime() - now.getTime() >= year_ms ) {
// A year away
} else {
// less than a year away
}

Categories

Resources