compare string with today's date in JavaScript - 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>

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);
});

Why does initializing a date object fail when I use a variable instead of integers or a string?

I am trying to create a new date object initialized to a date passed in from another function. The program will not know the desired date in advance, but let's say the date is January 1, 2017.
Successful:
var newYear = new Date(2017, 0, 1);
Logger.log(newYear.toISOString());
//logs 2017-01-01T08:00:00.000Z
Unsuccessful:
var date = "2017, 0, 1";
var newYear = new Date(date);
Logger.log(newYear.toISOString());
//throws "Error, date range is invalid."
Unsuccessful:
var date = "2017-0-1";
var newYear = new Date(date);
Logger.log(newYear.toISOString());
//throws "Error, date range is invalid."
Edit: Just before posting I figured it out. I hope no one minds me posting and answering my own question-- maybe you can answer it better!
Even though a string looks like a series of integers separated by commas, and even though Javascript is a loosely typed language, they are not the same.
Solution:
var year = 2017;
var month = 0; //don't forget months go from 0-11
var day = 1;
var newYear = new Date(year, month, day);
Logger.log(newYear.toISOString());
//logs 2017-01-01T08:00:00.000Z
To parse a date in the form of "2017-03-04":
var givenDate = "2017-3-04"
var date = givenDate.split("-");
var Year = date[0];
var Month = date[1]-1;
var Day = date[2];
var newYear = new Date(Year, Month, Day);
Logger.log(newYear.toISOString());
//logs 2017-01-01T08:00:00.000Z
Note: to output date in your local time zone, instead of "toISOString()", which reports the time as GMT/ISO time (on most browsers), you can use "toDateString()" to output a more readable form which is reflective of your local time zone.

Javascript: Get date string from raw date

I have another question on SO Unable to read date cell. This question is related to last question but more generic. How to convert Raw date, which represents number of days since 1st Jan 1900, to a javascript date type? [ Forget office365 ].
I have number of days elapsed since 1st Jan 1900. How can I get the date from it. For ex: I need a date after 42216 days, since 1st Jan 1900, How can I calculate that date? Answer is : 31-Jul-2015.
Try this:
(function(){
var date = new Date(1900,1,1);
var dayCount = 42216;
date.setDate(date.getDate() + dayCount)
console.log(date);
})()
Try this:
start = "01/01/1900"
newDate = start.split("/");
x = new Date(newDate[2]+"/"+newDate[1]+"/"+newDate[0]);
var numberOfDaysToAdd = 42216;
x.setDate(x.getDate() + parseInt(numberOfDaysToAdd));
var dd = x.getDate();
var mm = x.getMonth() + 1;
var yyyy = x.getFullYear();
var format = dd+'/'+mm+'/'+yyyy;
alert(format);
JSFIDDLE DEMO
Hope it help:
var dateStart= new Date('1900-01-01');
var afterDay=42216;
var newDay=new Date(dateStart.getTime() + afterDay*24*60*60*1000);
alert(newDay);

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.

Check the dates in 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]);

Categories

Resources