Date validation with JavaScript - javascript

I have a date string in this format - "DD-MM-YYYY"
this validates that successfully:
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ;
if(!startDate.match(dateFormat)){
alert("'Start Date' must be in format: DD-MM-YYYY");
return false;
I need to check that the inserted date is after today's date(or today's date).
how can i do that with JavaScript?
I've tried this:
http://www.redips.net/javascript/date-validation/
with the separator, didn't work. suggestions?

First, this is your current date in javascript:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // Zero indexed
All you need to do, from here, is to compare this with your start date!
Best regards!
check this out maybe it helps to understand the date object.

Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.

You could do this with moment.js pretty easily.
var input = moment(startDate, "DD-MM-YYYY");
if (input < moment()) {
// before today
} else {
// after today
}
We're also adding date validation pretty soon. See more info about validation here: https://github.com/timrwood/moment/pull/306

Something like this should work. Could use some cleanup, but hopefully gets the point across.
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(\d{4})/;
var dateMatch = startDate.exec(dateFormat);
var today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
if ((new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1])).getTime() >= today.getTime()) {
// Date is after or on today
}

You should check each date getTime() method and compare it. It's plain and simple, you don't need additional frameworks.
Here is an example that parses the dates from the strings, and then compares them:
var todayDate = "10-05-2012";​ // A sample date
var compareDate1 = "10-05-2012";
var compareDate2 = "03-05-2012";
var compareDate3 = "10-07-2012";
compareDates(todayDate, compareDate1);
compareDates(todayDate, compareDate2);
compareDates(todayDate, compareDate3);
function compareDates(date1String, date2String) {
var date1 = parseDate(date1String);
var date2 = parseDate(date2String);
if(date1.getTime() > date2.getTime()) {
alert("First date(" + date1String + ") is older than second date(" + date2String + ").");
} else if(date1.getTime() < date2.getTime()) {
alert("First date(" + date1String + ") is younger than second date(" + date2String + ").");
} else {
alert("The dates are the same day");
}
}
function parseDate(stringDateParam) {
var parsedDay = parseInt(stringDateParam.substring(0,2));
var parsedMonth = parseInt(stringDateParam.substring(3,5))-1;
var parsedYear = parseInt(stringDateParam.substring(6,10));
var parsedDate = new Date(parsedYear, parsedMonth, parsedDay, 0 , 0, 0, 0);
return parsedDate;
}
​
// Output:
//
// First check: The dates are the same day
// Second check: First date(10-05-2012) is older than second date(03-05-2012).
// Third check: First date(10-05-2012) is younger than second date(10-07-2012).
You probably already have a function that parses string to date object, and you should implement a check similar to the one in function compareDates based on getTime() function.
If you have further questions, leave a comment. Good Luck!
JSFiddle working example: click here

Thank you all!
this did the trick:
var today = new Date();
var Tday = today.getDate();
var Tmonth = today.getMonth()+1; // Zero indexed
var Tyear = today.getFullYear();
var aoDate;
var separator= '-';
aoDate = startDate.split(separator);
var month = aoDate[1] - 0;
var day = aoDate[0] - 0;
var year = aoDate[2] - 0;
if(year < Tyear){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month < Tmonth)){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month == Tmonth) && (day < Tday)){
alert("'Start Date' must be today or after today!");
return false;
}

Like most I was surprised a what js accepts as the constituent parts of a date. There may be holes in the code below which I would be glad to hear about but this seems to work for me. This assumes a DD/MM/YYYY HH:mm input format.
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1]);
}
// start of validation
var end_time = $('#tbDepartDtTm').val();
end_actual_time = strToDate(end_time);
// convert the date object back to a string in the required format
var dtString = ("0" + end_actual_time.getDate()).slice(-2) + "/" + ("0" + (end_actual_time.getMonth() + 1)).slice(-2) + "/" + end_actual_time.getFullYear() + " " + ("0" + end_actual_time.getHours()).slice(-2) + ":" + ("0" + end_actual_time.getMinutes()).slice(-2);
if (dtString != end_time) {
// if the string isn't the same as entered, it must be invalid. msg is a span element.
msg.textContent = "Depart date is not a valid date.";
return "Error";
}

Related

How to loop between dates that are in dmy format

Here is my 2 date
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
I want to loop between these two dates. So, i did like this
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
But i am getting unlimited loops running in browser.
How can i do this.
Note :
I don't want to use jQuery for this one.
If the start and end date is same it should loop only once and the input date will be always d/m/y format. What is the mistake in my code. Pls help
Update :
I have mistaken the date format, my date format is d-m-y. How can i do this for one..
Increment date by one day per iteration using getDate
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
In js month indexing starts at 0 so nov is 10 dec. is 11 and like so that's why i use getMonth() + 1
`
main problem is that you are not increasing your date.
here is the solution
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
You can make use of moment js and moment js duration. Its for duration purpose only. It very easy and meant for same.

Get Month as well as date in my variable - javascript

Hi i am trying to do a IF statement which allows the current date to be compared to the input date.. if the input date is below the current date it will be false.
I have got the date passing through my variable but it only stores the number so for example it compares day 9 to another day, which is not very reliable. I want the variable to take in the month and the year as well, meaning it can compare the ENTIRE DATE.
If there is a better way let me know.
Here is my code
if (this.element.find('#visitdate').length > 0) {
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
if (check < today) {
_errMsg = "Please enter a furture visit date";
return false;
} else {
return true;
}
}
Your line for today's date contains an error:
var today = new Date().getDate;
should be
var today = new Date().getDate();
format as mm/dd/yyyy
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
var today = new Date().getDate();
function isFromBiggerThanTo(dtmfrom, dtmto){
var from = new Date(dtmfrom).getTime();
var to = new Date(dtmto).getTime() ;
return from >= to ;
}
or using below
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
and compare
You can try this - it's working fine in my project -
Step 1
First Create javascript function as below.
Date.prototype.DaysBetween = function () {
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif / intMilDay);
if (intDays.toLocaleString() == "NaN") {
return 0;
}
else {
return intDays + 1;
}
}
Step 2
-
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
var dateDiff = check .DaysBetween(today);
// it will return integer value (difference between two dates )
if(dateDiff > 0 ){ alert('Your message.......');}
You can have this much easier.
You dont need to check with getDate() property you can just compare 2 dates.
And also is not needed to initialize with hours, minutes and seconds the Date, you only need year, month and date.
Here you have your example simplified
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0]);
var today = new Date();
if (check < today) {
return false;
} else {
return true;
}
http://jsfiddle.net/wns3LkLv/
Try this:
var user="09/09/2014/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date"); //do something
}else{
alert("userdate is after current date"); //do something
}
Thanks for all your answers guys i have fixed it.
I used the getTime function instead of getDate.
Then the check variable had to have a -1 assigned to the month as it was going 1 month to high.
var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0).getTime();
Cheers

How to parse date string in jQuery and check if it is in the past

I need to check if the date is in the past. This is what I have so far. JSfiddle here.
var date = "09/12/2013";
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = +(('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + d.getFullYear();
if (date < todaysDate) {
alert("in the past");
} else {
alert("in the future");
}
Currently it is saying that the date was in the past, when it should be in the future. I know I need to parse the string as a date, but not sure how.
Help?
With that input format, you can't use a string comparison, because the least significant values are on the left. Note: I'm assuing that date is December 9th, 2013. If you're doing the American thing where it's September 12th, 2013, you'll have to adjust the indexes into parts below.
You could reverse the fields:
var date = "09/12/2013";
var parts = date.split('/');
date = parts[2] + "/" + parts[1] + "/" + parts[0];
...and then do your string comparison (being sure to construct the string for "today" in the same order — year/month/day).
If you're going to do that, you could go ahead and finish the job
var date = "09/12/2013";
var parts = date.split('/');
var date = new Date(parseInt(parts[2], 10), // year
parseInt(parts[1], 10) - 1, // month, starts with 0
parseInt(parts[0], 10)); // day
if (date < new Date()) {
// It's in the past, including one millisecond ago
}
...but of course, if you don't want the expression to be true for one millisecond ago, your string approach is fine.
var date = new Date("09/12/2013");
var d = new Date();
console.log(date>d); // true
var date = new Date("09/12/2011");
console.log(date>d); // false
JavaScript's native Date comparator only works on Date objects, whereas you are comparing Strings. You should parse date into a Date object, and then compare it with d.
//define parse(string) --> Date
if(parse(date) < new Date()) {
alert('past');
} else {
alert('future');
}

Compare dates are not returning correct results in javascript

I am comparing two dates in javascript
function checkCurrentDate(expiryDate){
//var currentDateStr=expiryDate;
var currentDate = new Date();
var month = currentDate.getMonth() + 1;
var day = currentDate.getDate();
var year = currentDate.getFullYear();
currentDate = month + "/" + day + "/" + year;
var dArr = currentDate.split("/");
currentDate = dArr[0]+ "/" +dArr[1]+ "/" +dArr[2].substring(2);
var currentExpiryDateStr = expiryDate;
if(currentExpiryDateStr == currentDate){
}
if(currentExpiryDateStr < currentDate){
alert("Expiry date is earlier than the current date.");
return false;
}
}
currently the dates are in "currentExpiryDateStr " is "11/10/12" and "currentDate" is "11/8/12" now in this condition "if(currentExpiryDateStr < currentDate)" is returning true and is entering in if condition but this condition should return false and should not enter in this if condition. It was working before but dont know why it is not working now.
The Date object will do what you want - construct one for each date, then just compare them using the usual operators.
try this..
function checkCurrentDate(expiryDate){
var currentDate = new Date(); // now date object
var currentExpiryDateStr = new Date(expiryDate); //expiry date object
if(currentExpiryDateStr == currentDate){
}
if(currentExpiryDateStr < currentDate){
alert("Expiry date is earlier than the current date.");
return false;
}
}
here is the fiddle:: http://jsfiddle.net/YFvAC/3/
var currentDate = Date.now();
if (expiryDate.getTime() < currentDate ) {
alert("Expiry date is earlier than the current date.");
return false;
}
The now() method returns the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now as a number.
The getTime() returns the Milliseconds since midnight January 1, 1970
You are comparing strings, you should be comparing date objects.
If the expriy date is '11/10/12' in the format month/day/year and that the year is a two digit year after 2000, you can convert that to a date using:
function mdyToDate(dateString) {
var b = dateString.split(/\D/);
return new Date('20' + b[2], --b[0], b[1]);
}
To test expiry, you can do something like:
function hasExpired(dateString) {
var expiryDate = mdyToDate(dateString);
var now = new Date();
return now > expiryDate;
}
So on 8-Nov-2012:
hasExpired('11/10/12'); // 10-Nov-2012 -- false
hasExpired('6/3/12'); // 03-Jun-2012 -- true
The hasExpired function can be replace with:
if (new Date() > mdyToDate(dateString)) {
// dateString has expired
}
Just add this 2 lines before your if condition
currentExpiryDateStr=Date.parse(currentExpiryDateStr);
currentDate=Date.parse(currentDate);

If month is not current month

We have a .NET web service which returns JSON, including a date in string format as follows: 2012-04-30T00:00:00+12:00.
In javascript, I want to exclude dates where the month is not the current month. Hence, with the above date, the month is 04 (April) and the current month is May (in New Zealand anyway). So, I want to ignore this record, e.g, in pseudocode:
if(vMonth == CurrentMonth){
dothis();
}
How can I do this?
EDIT: See Rob G's answer below for the solution that works in all browsers.
var dateOne = new Date("2012-04-30T00:00:00+12:00");​​​
var dateTwo = new Date();
if(dateOne.getMonth() == dateTwo.getMonth()) {
alert("equal");
}
Here's the jsfiddle:
http://jsfiddle.net/Mq5Tf/
More info on the date object:
MSDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
ES5: http://es5.github.com/#x15.9.2
var date = new Date();
var currentMonth = date.getMonth();
var yourMonth = 4;
if(yourMonth == currentMonth ){
/* Do this */
alert('Hello');
}
An alternative that doesn't depend on parsing the date string:
function checkMonth(ds) {
var now = new Date();
var m = now.getMonth() + 1;
return !!ds.match(now.getFullYear() + '-' + (m<10?'0':'') + m);
}
// on 2012-05-01
alert( checkMonth('2012-04-30T00:00:00+12:00') ); // false
alert( checkMonth('2012-05-01T00:00:00+12:00') ); // false
Edit
Note that checking the month number only works where the timezone offset should be ignored or is not significant. While 2012-04-30T00:00:00+12:00 is in April, 2012-04-30T14:00:00+12:00 will be 2am on 1 May local time.
// Means April 30, months are indexes in JS
var input = new Date(2012, 03, 30);​​​
// or use format new date("2012-04-30T00:00:00+12:00") suggested in other answer
var currentDate = new Date();
if(input.getFullYear() == currentDate.getFullYear() // if you care about year
&& input.getMonth() == currentDate.getMonth()) {
// act accordingly
}

Categories