JavaScript validation for datetime combination comparing - javascript

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

Related

How to subtract two different dates from a date/time stamp?

I need to subtract a date like 1/26/2015 from a date-time like 2016-01-27T01:10:57.569000+00:00. From what I've read converting both to distance in milliseconds from Epoch and then subtracting is the easiest way. I've tried using various methods, but all the methods seem to say 2016-01-27T01:10:57.569000+00:00 is invalid data. The method .getTime() works great for the 1/26/2015 format, but it can't read the 2016-01-27T01:10:57.569000+00:00.
How does one go about getting the date/time UTC time into milliseconds?
On a complicated way you can use a regex to extract each part of the date as string and then use them in a new Date with all parameters:
function getTimeDifference(){
var regEx = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):([\d.]+)/;
var dateString = '2016-01-27T01:10:57.569000+00:00';
var r = regEx.exec( dateString );
var date1 = new Date(r[1], r[2]-1, r[3], r[4], r[5], r[6]); // Notice the -1 in the month
var date2 = new Date('1/26/2015');
var difference = date1 - date2;
Logger.log(difference);
}
I ended up using this. When I call parseDate(), I used getTime() to get the date in milliseconds then subtracted them and converted them to days. For my use case the time didn't have to be down to the second, but if it did, it wouldn't be hard to parse more info from the string. I ran into trouble initially because as a beginner Javascript writer I didn't know why apps script wouldn't accept this format into the date constructor.
function parseDate(str) {
//This should accept 'YYYY-MM-DD' OR '2016-01-27T01:10:57.569000+00:00'
if(str.length == 10){
var mdy = str.split('-');
return new Date(mdy[0], mdy[1]-1, mdy[2]);
}
else
{
var mdy = str.split('-');
var time = mdy[2].split('T');
var hms = time[1].split(':');
return new Date(mdy[0], mdy[1]-1, time[0], hms[0], hms [1]);
}
}
If you are confident that the values in the date strings will always be valid and that the ISO8601 string will always have offset 00:00 (i.e. UTC), then simple parse functions are:
// Parse ISO 8601 format 2016-01-27T01:10:57.569000+00:00
function parseISOUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5],b[6]));
}
document.write(parseISOUTC('2016-02-04T00:00:00.000+00:00'));
// Parse US format m/d/y
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2],b[0]-1,b[1]);
}
document.write('<br>'+ parseMDY('2/4/2016'))
document.write('<br>'+ (parseISOUTC('2016-02-04T00:00:00.000+00:00') - parseMDY('2/4/2016')))
Note that the first string is UTC and the second will be treated as local (per ECMAScript 2015), so the difference between 2016-02-04T00:00:00.000+00:00 and 2/4/2016 will be the time zone offset of the host system.

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 - Convert string to date and compare dates

I have date from the date picker which I am accessing as -
var transdate = $j("input[name='enterdate']").val();
resulting in transdate = "6/22/2015"
I need to test if the entered date is between two dates which are defined as
startdate = '2015-02-01' and enddate = '2015-07-30'
How do I convert the transdate in yyyy-mm-dd format in the following code -
if ((new Date('transdate')>= startdate ) && (new Date('transdate') <= enddate )) {
alert("correct date entered");
}
Moment.js is a small handy library for dates that makes this easy.
moment('6/22/2015', 'M/D/YYYY')
.isBetween('2015-02-01', '2015-07-30'); // => true
Note that only the first (US format) date string needed an explicit format string supplied.
Moment can be useful for the parsing alone, eg. even if not using isBetween:
var transdate = moment('6/22/2015', 'M/D/YYYY').toDate();
var startdate = moment('2015-02-01').toDate();
var enddate = moment('2015-07-30').toDate();
transdate >= startdate && transdate <= enddate // => true
The string is not in the only format defined to be handled by the Date object. That means you have to parse it (with regular expressions or String#split or whatever), or use a library like MomentJS that will parse it for you. Once you've parsed the dates, you can compare them with < or >, etc.
Do not rely on Date to parse strings it's not defined to parse. You will run into implementations or locales where it doesn't work.
"6/22/2015" is trivial to parse with a regular expression:
var rex = /^(\d+)\/(\d+)\/(\d+)$/;
var match = rex.exec(transdate);
var dt = match ? new Date(+match[3], +match[1] - 1, +match[2]) : null;
That uses the Date constructor that accepts the parts of the date as individual numeric arguments (year, month, day). The + converts strings to numbers. The [x] are capture groups from the regex. You have to subtract one from the month because months start with 0 in JavaScript.
Similar questions have been asked many, many times but I can't seem to find a duplicate. Given the unreliability of the Date constructor to parse strings, the simplest solution is to parse the string yourself:
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[0]-1, b[1]);
}
Here is the JSFIDDLE of you output.
Moment.js will give you good flexibility in coding.
Dont forget to add jquery and moment.js in your html
var transdate="6/22/2014";
var convertStringToValidDate = new Date(transdate);
$(document).ready(function(){
$("#selectedDate").text(transdate);
$("#validDate").text(convertStringToValidDate);
converttoformat = moment(convertStringToValidDate).format("YYYY-MM-DD");
$("#converttoyyyymmdd").text(converttoformat);
if(moment(converttoformat).isBetween('2015-02-01', '2015-07-30')){
$("#result").text("Date lies in between");
}
else{
$("#result").text("Date is out of scope");
}
});

javascript / jquery compare datetime values

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

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

Categories