javascript / jquery compare datetime values - javascript

Seems to be a simple and commonly asked question but after googling for a while havent come up with an answer.
Very simply, I have two variables each with a datetime value in format yyyy-mm-dd hh:mm
I want to compare which is bigger and perform logic accordingly:
example: here
var fromDate = '2014-02-14 07:00';
var toDate = '2014-02-14 07:00';
if (Date.parse(fromDate) > Date.parse(toDate)) {
alert("Invalid Date Range!\nStart Date cannot be after End Date!")
} else {
alert("VALID Date Range!\n Start Date is before End");
}
The above continuously returns the successful validation.
Any advice, suggestions? examples? Thanks,

It happens that the format you're using can be compared lexigraphically. So no parsing required:
var fromDate = '2014-02-14 07:00';
var toDate = '2014-02-14 07:00';
if (fromDate > toDate) {
alert("Invalid Date Range!\nStart Date cannot be after End Date!");
} else {
alert("VALID Date Range!\n Start Date is before End");
}
This is because the most significant fields precede the less significant fields, throughout the string.
But if you really want date/time values, that string format isn't directly supported by the specification. You have three choices:
Use a library like MomentJS.
Massage the string so that it's in a supported format, but be aware that until ES5, there was no standard format dictated by the spec.
Do it yourself
The latter looks something like this:
function parseMyDate(str) {
var parts = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/.exec(str);
if (!parts) {
return null;
}
return new Date(parseInt(parts[1], 10), // Year
parseInt(parts[2], 10) - 1), // Month
parseInt(parts[3], 10), // Day
parseInt(parts[4], 10), // Hours
parseInt(parts[5], 10)); // Minutes
}
Then use parseMyDate where you have Date.parse above.

this is real ugly but serves the purpose...
var fromDate = '2014-02-27 09:00';
fromDate=fromDate.replace("-", "/");
fromDate=fromDate.replace("-", "/");
var toDate = '2014-02-27 10:00';
toDate=toDate.replace("-", "/");
toDate=toDate.replace("-", "/");
var fromDate=(new Date(fromDate).getTime()/1000);
var toDate=(new Date(toDate).getTime()/1000);
if(fromDate>toDate){
alert('CORRECT');
} else {
alert('INCORRECT, from after to');
}

Related

Javascript: check date in future in dd/mm/yyyy format?

I'm trying to check the users input field to see if it is in the future and if it is in dd/mm/yyyy format but I have no idea why the format part of my code doesn't fire at all! In fact nothing seems to be working on Jsfiddle but at least my "check date in the future" function works locally.
I don't know the correct way of going about this.
to explain this, I've created this FIDDLE
And this is my full javascript code. I need to stay with pure javascript by the way:
function checkdate(){
//var sendDate = document.getElementById('send_year').value + '/' + document.getElementById('send_month').value + '/' + document.getElementById('send_day').value;
var sendDate = document.getElementById('returning_date').value;
sendDate = new Date(Date.parse(sendDate.replace(/-/g,' ')))
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById('error8').innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById('error8').innerHTML = '';
}
if(sendDate.match(/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/))
{
alert('works out');
}
}
could someone please advise on this issue?
Thanks in advance.
One problem is that you are trying to run sendDate.match, but sendDate has been converted into a Date object so it does not have a match method.
You should run your regular expression before you convert it to a Date, in validation, you typically check that the input conforms to a format before you run further validation like range validation.
Date strings should always be manually parsed, you should never allow the Date constructor or Date.parse to parse strings (the Date constructor parses strings in exactly the same way Date.parse does).
To parse and validate a date string is fairly straight forward, just parse the string and see if you get a valid date:
/* Parse a string in d/m/y format. Separator can be any non–digit
** Avoid conversion of two digit dates to 20th century
** Returns an invalid Date if string is not a valid date (per ECMA-262)
**
** #param {string} s - Date string to parse
** #returns {Date}
*/
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Test valid date
document.write(parseDMY('23/01/2016'));
// Test invalid date
document.write('<br>' + parseDMY('35/12/2016'));
Note that this will accept a date like 1/5/16 and treat is as 1 May, 0016. If you want to guarantee that the day and month values have two digits and the year for, then add:
/^\d\d\D\d\d\D\d{4}$/.test(s)
to the validation test at the end. However, I don't like forcing 2 digits for day and month as people don't usually write dates as "01/08/2016", they use "1/8/2016".
First of all, the function needs to be wrapped in <head> (hit the cog in the js tab), otherwise the function can't be found.
But your main problem is that you are using European style of date formatting, so you'll get a "Invalid Date" exception when creating the date. Refer to this question on how to convert it to USA-style and make it available for the Date object (check the reference for all possible uses)
My proposal is:
Date.prototype.fromString = function(str) {
var m = str.match(/([0-9]{2})(-|\/)([0-9]{2})(-|\/)([0-9]{4})/);
if (m == null) {
return null;
}
for (var i = 0; i < m.length; i++) {
if (typeof(m[i]) === 'undefined') {
return null;
};
};
var year = parseInt(m[5]);
var month = parseInt(m[1]) - 1;
var day = parseInt(m[3]);
if (month == 0 || day == 0) {
return null;
}
return new Date(year, month, day);
}
function checkdate(e, obj, errMsgSel){
var sendDate =obj.value;
sendDate = (new Date()).fromString(sendDate);
if (sendDate == null) {
if (e.type == 'blur') {
obj.value = '';
}
return;
}
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById(errMsgSel).innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById(errMsgSel).innerHTML = '';
}
} $(function () {
});
<input onblur="checkdate(event, this, 'error8');" onKeyUp="checkdate(event, this, 'error8');" type='text' name="text1" placeholder='dd/mm/yyyy' id='returning_date'>
<span id='error8' style='color:red;'>format</span> <br><Br>

javascript date validation is not working for today date

I have got below java script code that will validates date range ... when the user entered the today date or any future dates I have set IsValid to true and then will do the save operation ....
for that purpose I have written below code ..
function Save(e) {
var popupNotification = $("#popupNotification").data("kendoNotification");
var container = e.container;
var model = e.model;
var isValid = true;
var compareDate = e.model.DeliveryDate;
alert(compareDate);
var todayDate = new Date();
var compareDateModified = new Date(compareDate)
alert(compareDateModified);
if (compareDateModified > todayDate || compareDateModified === todayDate) {
isValid = true;
}
else
isValid = false;
e.preventDefault();
if (isValid == false)
{
popupNotification.show("Delivery Date should be today date or Greater", "error");
}
$('#Previous').show();
$('#Next').show();
}
Its working fine when I give the future dates but its not working for today date. I also need to check the today's date. I am not able to figure it out the error alert when I try to enter to the today date .
You are comparing two objects of the same type, but different objects, so that will always result in 'unequal'
If you use date.getTime() you will get better results in your comparison - but only if the time component is the same of course.
Think of the Date object like a timestamp. It is based on the unix-style of timestamps (the amount of seconds since 1st January, 1970) so the Date object isn't the day, it is the Date AND the Time.
What you're comparing is the times as well, which could get a little iffy. If only days matter, try using:
fullCompareDate = compareDateModified.getFullYear() + "/" + compareDateModified.getMonth() + "/" + compareDateModified.getDate();
fullTodayDate= todayDate.getFullYear() + "/" + todayDate.getMonth() + "/" + todayDate.getDate();
if(compareDateModified>todayDate||fullCompareDate==fullTodayDate)
{
//Do something
}
This will compare the date and time to make sure they are greater OR check the current date with the compare date (as strings)
Another solution is to blank out the times on both dates:
compareDateModified.setHours(0,0,0,0);
todayDate.setHours(0,0,0,0);
if(compareDateModified>=todayDate)
{
//Do something
}
You are comparing the compareDateModified to todayDate on the millisecond level. To compare at the day level:
var todayDate = new Date();
todayDate.setHours(0,0,0,0);
//you may also have to truncate the compareDateModified to the first
//second of the day depending on how you setup compareDate
if (compareDateModified >= todayDate) {
isValid = true;
}

JavaScript validation for datetime combination comparing

I have two dates i want to throw an alert if astart date is less than enddate
format i use dd/mm/yyyy
time 24 hrs format :HH:MM:SS
var strt_date = 31/03/2014 23:02:01;
var end_date = 01/04/2014 05:02:05;
if(Date.parse(strt_date) < Date.parse(end_date))
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
See the following answer: Compare two dates with JavaScript
Essentially you create two date objects and you can compare them.
var start_date = new Date('31/03/2014 23:02:01');
var end_date = new Date('31/03/2014 23:02:01');
if (end_date < start_date) {
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
(from reading the linked answer it is possible using the Date::gettime method for comparison purposes may be faster than the actual comparing of date objects)
Your timestamps are not quoted as strings, which is throwing a syntax error, add single quotes to them:
var strt_date = '31/03/2014 23:02:01';
var end_date = '01/04/2014 05:02:05';
if((new Date(strt_date)).getTime() < (new Date(end_date)).getTime())
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
Using .getTime() will compare as numbers, so you can determine if the start date has a greater number than the end date.
DEMO
Try to use the folowing format: Date.parse("YEAR-MONTH-DAYTHOURS:MINUTES:SECONDS")
var strt_date = "2014-03-31T23:02:01";
var end_date = "2014-04-01T05:02:05";
if(Date.parse(strt_date) < Date.parse(end_date))
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}

How to check if input date is equal to today's date?

I have a form input with an id of 'date_trans'. The format for that date input (which is validated server side) can be any of:
dd/mm/yyyy
dd-mm-yyyy
yyyy-mm-dd
yyyy/mm/dd
However, before posting the form, I'd like to check if the date_trans field has a date that is equal to today's date. Its ok if the date taken is the client's date (i.e. it uses js), since I run a double check on the server as well.
I'm totally lost on how to do the date comparrison in jQuery or just plain old javascript. If it helps, I am using the jquery datepicker
A simple date comparison in pure JS should be sufficient:
// Create date from input value
var inputDate = new Date("11/21/2011");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
// Date equals today's date
}
Here's a working JSFiddle.
for completeness, taken from this solution:
You could use toDateString:
var today = new Date();
var isToday = (today.toDateString() == otherDate.toDateString());
no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho
Try using moment.js
moment('dd/mm/yyyy').isSame(Date.now(), 'day');
You can replace 'day' string with 'year, month, minute' if you want.
function sameDay( d1, d2 ){
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate();
}
if (sameDay( new Date(userString), new Date)){
// ...
}
Using the UTC* methods ensures that two equivalent days in different timezones matching the same global day are the same. (Not necessary if you're parsing both dates directly, but a good thing to think about.)
Just use the following code in your javaScript:
if(new Date(hireDate).getTime() > new Date().getTime())
{
//Date greater than today's date
}
Change the condition according to your requirement.Here is one link for comparision compare in java script
The following solution compares the timestamp integer divided by the values of hours, minutes, seconds, millis.
var reducedToDay = function(date){return ~~(date.getTime()/(1000*60*60*24));};
return reducedToDay(date1) == reducedToDay(date2)
The tilde truncs the division result (see this article about integer division)
Date.js is a handy library for manipulating and formatting dates. It can help in this situation.
Try this
// method to check date is less than today date
isLessDate(schedule_date : any){
var _schedule_date = new Date(schedule_date);
var date = new Date();
var transformDate = this.datePipe.transform(date, 'yyyy-MM-dd');
var _today_date = new Date(''+transformDate);
if(_schedule_date < _today_date){
return 'small'
}
else if(_schedule_date > _today_date){
return 'big'
}
else {
return 'same'
}
}
The Best way and recommended way of comparing date in typescript is:
var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();
if(today === reqDateVar){
// NOW
} else {
// Some other time
}
TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}
< = also works, Although with =, it might have to match the milliseconds.
There is a simpler solution
if (inputDate.getDate() === todayDate.getDate()) {
// do stuff
}
like that you don't loose the time attached to inputDate if any

Using Javascript, how do I make sure a date range is valid?

In JavaScript, what is the best way to determine if a date provided falls within a valid range?
An example of this might be checking to see if the user input requestedDate is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.
This is actually a problem that I have seen come up before a lot in my works and the following bit of code is my answer to the problem.
// checkDateRange - Checks to ensure that the values entered are dates and
// are of a valid range. By this, the dates must be no more than the
// built-in number of days appart.
function checkDateRange(start, end) {
// Parse the entries
var startDate = Date.parse(start);
var endDate = Date.parse(end);
// Make sure they are valid
if (isNaN(startDate)) {
alert("The start date provided is not valid, please enter a valid date.");
return false;
}
if (isNaN(endDate)) {
alert("The end date provided is not valid, please enter a valid date.");
return false;
}
// Check the date range, 86400000 is the number of milliseconds in one day
var difference = (endDate - startDate) / (86400000 * 7);
if (difference < 0) {
alert("The start date must come before the end date.");
return false;
}
if (difference <= 1) {
alert("The range must be at least seven days apart.");
return false;
}
return true;
}
Now a couple things to note about this code, the Date.parse function should work for most input types, but has been known to have issues with some formats such as "YYYY MM DD" so you should test that before using it. However, I seem to recall that most browsers will interpret the date string given to Date.parse based upon the computers region settings.
Also, the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven.
So if i understand currenctly, you need to look if one date is bigger than the other.
function ValidRange(date1,date2)
{
return date2.getTime() > date1.getTime();
}
You then need to parse the strings you are getting from the UI, with Date.parse, like this:
ValidRange(Date.parse('10-10-2008'),Date.parse('11-11-2008'));
Does that help?
var myDate = new Date(2008, 9, 16);
// is myDate between Sept 1 and Sept 30?
var startDate = new Date(2008, 9, 1);
var endDate = new Date(2008, 9, 30);
if (startDate < myDate && myDate < endDate) {
alert('yes');
// myDate is between startDate and endDate
}
There are a variety of formats you can pass to the Date() constructor to construct a date. You can also construct a new date with the current time:
var now = new Date();
and set various properties on it:
now.setYear(...);
now.setMonth(...);
// etc
See http://www.javascriptkit.com/jsref/date.shtml or Google for more details.

Categories