Through the form i am getting two values like
Start datetime = '01/12/2013 12:00:00 AM' and
End datetime = '02/12/2013 12:00:00 AM'.
How I can validate the start datetime must be less than end datetime in javascript?
Asuming you received a date in Javascript Date format you need Date.parse() function or compare by comparison operators. It will return the milliseconds that have passed since 01/01/1970 00:00
Somehow like this:
if(Date.parse(datetimeStart) < Date.parse(datetimeEnd)){
//start is less than End
}else{
//end is less than start
}
Here is a Fiddle
its really simple in javascript
var startTime = new Date('01/12/2013 12:00:00 AM');
var endTime = new Date('02/12/2013 12:00:00 AM');
and then all you need to do is compare
if( startTime < endTime){
alert("start time is lesser");
}
More on this here
Try this following code:
function dateCheck() {
var fDate = new Date("26/05/2013");
var lDate = new Date("24/05/2013");
if(fDate <= lDate) {
alert("true");
return true;
}
alert("false");
return false;
}
//StartDate & EndDate two dates
if (StartDate < EndDate)
// code
if you just want the dates, and not the time
if (StartDate.Date < EndDate.Date)
// code
If you want to compare only dates then this will work.
var dt1 = new Date('12/31/2013');
var dt2 = new Date('12/31/2014');
var dt1obj = Date.parse(dt1);
var dt2obj = Date.parse(dt2);
if(dt2obj <= dt1obj){
//your code here...
}else{
//your code here...
}
var record_day1=fromDate.split("/");
var sum1=record_day1[1]+'/'+record_day1[0]+'/'+record_day1[2];
var record_day2=toDate.split("/");
var sum2=record_day2[1]+'/'+record_day2[0]+'/'+record_day2[2];
var record1 = new Date(sum1);
var record2 = new Date(sum2);
if(record2 < record1)
{
alert("End date must be greater than start date");
return false;
}
Here we are splitting the date and then combining it for comparing it hope it will work thanks.....:)
use the date object
Date1 = new Date('01/12/2013 12:00:00 AM');
Date2 = new Date('02/12/2013 12:00:00 AM');
Date1-Date2//in millisecond
You can use Date.parse as following
if (Date.parse(datetimeStart) < Date.parse(datetimeEnd)) {} else {}
Related
I know this has been asked before but I can't get it to work due to my date format, which I can't change. Any help would be appreciated.
My date is in this format;
4/11/2017 12:30 PM.
If I inspect it in the developer tools it shows it as
4/11/2017 12:30 PM EDIT: Won't show with prepended space here
i.e. with a space in front, not sure if that's relevant.
Does anyone know if it's possible or how to compare it with today's date to see if it's in the past or future?
I've tried tinkering with the following code but can't get it to work because of the time, PM, and forward slashes.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d,m,y);
mydate=new Date('13/04/2017');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
If you have dates that are in the same format of something like 13/04/2017, you could split the string based on the slashes and compare the values starting from the right moving left.
By this, I mean when you have your array of three values for each date, you could first compare the year, if that's the same, move on to comparing the month, if that's the same then on to comparing the day.
But if for instance one of the year's is 2018 while the other is 2016, you would immediately know that the 2018 one comes later.
var st = "19/05/2019";
var st2 = "19/05/2019";
function provideLaterDate(date1, date2) {
var splitDateDate1 = date1.split("/").reverse();
var splitDateDate2 = date2.split("/").reverse();
var laterDate = false;
splitDateDate1.forEach(function(val, idx, arr) {
if ( laterDate === false ) {
if ( val > splitDateDate2[idx] ) {
laterDate = splitDateDate1;
} else if ( val < splitDateDate2[idx]) {
laterDate = splitDateDate2;
} else {
laterDate = "Both are the same";
}
}
});
if ( /\//.test(laterDate) ) {
return laterDate.reverse().join("/");
} else {
return laterDate;
}
}
To get rid of the "time pm" part, you could simply do something like:
// Assuming your date has a structure like this: 4/11/2017 12:30 PM.
var newDate = unformattedDate.split(" ")[0];
// This will separate your date string by spaces, and since there are no spaces until after the year in your date, the 0 index will give you the date minus the time and pm portion. Please pardon the not-consistent variable names.
The problem was with the way you were constructing date. Construct date like this var mydate = new Date(2017, 04, 03); and it works.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d, m, y);
var mydate = new Date(2017, 04, 03);
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
}
else {
alert("smaller")
}
You can split the date. Be aware you should contruct your date as follows:
var date = new Date(y,m,d);
Means year first, then month and finally day, as you can see under https://www.w3schools.com/jsref/jsref_obj_date.asp
You can use the following code to perform what you want:
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
newdate = '13/04/2017'
array = newdate.split('/');
var d1 = array[0]
var m1 = array[1]-1
var y1 = array[2]
mydate = new Date(y1,m1,d1);
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can always check the date created is correct by using the date.toString() function. Be aware 0=January for month as you can check under https://www.w3schools.com/jsref/jsref_getmonth.asp. That's why I added the -1 for var m1.
Problem:
It's not working because you are comparing a date with an Invalid date, it will always return false.
Explanation:
And the Invalid date comes from the line new Date('13/04/2017'), because 13 is expected to be a month number and not a day which is an invalid month, because the new Date(stringDate) will be treated as a local Date and not a UTC date by the browser, and it depends on which browser you are using.
You can see in the JavaScript Date Specification that:
parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Demo:
So if we change new Date('13/04/2017') to new Date('04/13/2017') the code will work as expected:
var date = new Date();
var mydate = new Date('04/13/2017');
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
} else {
alert("smaller")
}
if(date.getTime()>mydate.getTime()){
alert("greater");
}
else if (date.getTime()==mydate.getTime){
alert("simmilar");
else {alert("smaller");}
I have a form where the user has to input one begin date and one end date. After that, I have to compute the result of this date to have a status on the UI:
if dates are in the past, status is "DONE"
if dates are in the future, status is "TO BE DONE"
if today is bewteen the two dates, status is "IN PROGRESS"
How can I compute that easely? I have date in the form with that format: 04/21/2015.
Do you recommand me to compare date by changing format (04/21/2015 => 20150421) and compare? Or use Date of JS? or anything else?
Thanks in advance
Get two date objects like this:
// parse a date in mm/dd/yyyy format
function parseDate(input) {
var parts = input.split('/');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[2], parts[0]-1, parts[1]); // Note: months are 0-based
}
Then compare using usual operators < > ==
You can create a date object for the input date and another date object for the current date and then, simply compare them.
Check the dateObject in order to provide the correct date string format:
var inpDate = $('input').val();
var d = new Date(inpDate);
var today = new Date();
if (inpDate > today) {
return "TO BE DONE";
} else ....
have you tried http://momentjs.com/ . Real easy to use, conversion and formatting could save you time adding further JavaScript code however it is offset by adding the library.
function getStatusByDate(startDate, endDate) {
var currentTime = new Date().getTime();
var startTime = new Date(startDate).getTime();
var endTime = new Date(endDate).getTime();
console.log(startTime, endTime);
if (startTime < endTime && endTime < currentTime) {
return ('DONE');
} else if (startTime < endTime && endTime > currentTime && startTime < currentTime) {
return ('IN PROGRESS');
} else if (startTime < endTime && startTime > currentTime) {
return ('TO BE DONE');
} else {
return ('INVALID INPUT');
}
}
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);
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
}
I am trying to compare two dates. I have this code which I thought would work a treat, but it didn't. For now I just want to alert with an error if the end date is less than the start date. The date style, yyyy-mm-dd, needs to be kept in this format for other events prior to this. What is wrong with this code?
startdate = "2009-11-01" ;
enddate = "2009-11-04" ;
var d1 = new Date(startdate)
var d2 = new Date(enddate)
if (d2 < d1) {
alert ("Error ! ) ;
}
document.cookie='st =' + startdate // set sytem cookie
document.cookie='en =' + enddate
window.location = self.location.href
window.opener.location.reload()
close()
Try using DateJS, an open-source JavaScript Date Library that can handle pretty much everything! The following example is working:
<script type="text/javascript" src="date.js"></script>
<script>
startdate = "2009-11-01";
enddate = "2009-11-04";
var d1 = Date.parse(startdate);
var d2 = Date.parse(enddate) ;
if (d1 < d2) {
alert ("Error!");
}
</script>
Someone finally uses ISO 8601 standard dates but then ...
You are using a nice international standard that JavaScript arguably should understand. But it doesn't.
The problem is that your dates are in ISO 8601 standard format which the built-in Date.parse() can't read.
JavaScript implements the older IETF dates from RFC 822/1123. One solution is to tweak them into the RFC-style, which you can see in RFC1123, and which look like dd month yyyy.
There is coding floating about that can scan the ISO format comprehensively, and now that you know to google for "iso standard date" you can get it. Over here I found this:
Date.prototype.setISO8601 = function (string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
}
js> t = new Date()
Sun Nov 01 2009 09:48:41 GMT-0800 (PST)
js> t.setISO8601("2009-11-01")
js> t
Sat Oct 31 2009 17:00:00 GMT-0700 (PDT)
The 11-01 is reinterpreted in my timezone, as long as all your dates get the same conversion then they should compare reasonably, otherwise you can add TZ info to your string or to the Date object.
The Date constructor cannot parse that format, and since you cannot change it, you should parse it manually, and pass the year, month and date parts to it, for example:
function compareDates(startDate, endDate) {
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
if (parseDate(endDate) < parseDate(startDate)) {
alert ("Error !");
}
}
Usage:
var startDate = "2009-11-01",
endDate = "2009-11-04";
compareDates(startDate, endDate);
var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}
source: http://www.w3schools.com/jS/js_obj_date.asp
If you only need to know if one date comes before the other, you could just use the Date object's getTime() method to compare their respective numbers of milliseconds since midnight Jan 1, 1970:
if( d2.getTime() < d1.getTime() )
{
alert("eeeek!");
}
--- Don't get mixed up and try to use getMilliseconds(), though :)
w3schools documentation on getTime()
USe this function for date comparison in javascript:
function fn_DateCompare(DateA, DateB) {
var a = new Date(DateA);
var b = new Date(DateB);
var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());
var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());
if (parseFloat(msDateA) < parseFloat(msDateB))
return -1; // less than
else if (parseFloat(msDateA) == parseFloat(msDateB))
return 0; // equal
else if (parseFloat(msDateA) > parseFloat(msDateB))
return 1; // greater than
else
return null; // error
}
I implemented the below code for a date comparison depending on current time - -
// get the current time from a hidden input which is being set by server time
// because client may have a wrong time
var ch = jQuery('#clockHours').val(); // e.g. 9,10 etc.
ch = parseInt(ch);
// get the today's date from a server value as well
var td = jQuery('#clockDate').val(); // may be => new Date(); e.g. 2014-05-15
td = Date.parse(td);
td.setHours(0, 0, 0, 0);
// get the input date
var inpdate = jQuery('#jform_in_date').val(); // may be => new Date(); e.g. 2014-05-15
inpdate = Date.parse(inpdate);
inpdate.setHours(0, 0, 0, 0);
// get yesterday's date. this is from server as well
yd = new Date();
yd.setFullYear(td.getFullYear(), td.getMonth(), td.getDate()-1);
yd.setHours(0, 0, 0, 0);
alert('today\'s date is: '+td.toString());
alert('yesterday\'s date is: '+yd.toString());
// if it is not 10 AM then dates from yesterday are valid
if(ch <= 9) {
if(inpdate.getTime() >= yd.getTime()) {
alert('Valid: dates from yesterday are allowed');
} else {
alert('Invalid: dates before yesterday are not allowed');
}
} else {
if(inpdate.getTime() >= td.getTime()) {
alert('Valid: dates from today are allowed');
} else {
alert('Invalid: dates before today are not allowed');
}
}
I hope this will help very clearly.