Set validation to check two dates with javascript - javascript

I am trying to find the difference between two dates,when the user wants to change arrival date, remember the number of days between arrival/departure before the change , after changing arrival date , automatically set departure date to be x days after arrival date ,
So, if i have 01JUN17 - 05JUN17 (4days) and the user changes the arrival date to 04JUN17 then set departure to 08JUN17 (+4 days)
function changedDate() {
var startDate = $("#Arrival").val().split("-");
var endDate = $("#Departure").val().split("-");
var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
var timeDiff = Math.abs(departureDate.getDate() - arrivalDate.getDate());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (arrivalDate >= departureDate) {
var arrDate = arrivalDate;
arrDate.setDate(arrDate.getDate() + 1);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
$("#Departure").val(day + '-' + month + '-' + year);
}
if (timeDiff > 1) {
var arrDate = arrivalDate;
var depDate = departureDate;
arrDate.setDate(arrDate.getDate());
depDate.setDate(depDate.getDate() + diffDays);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
var monthd = depDate.getMonth() + 1;
if (monthd < 10)
monthd = '0' + month;
var dayd = depDate.getDate();
if (dayd < 10)
dayd = '0' + day;
var yeard = depDate.getFullYear();
$("#Arrival").val(day + '-' + month + '-' + year);
$("#Departure").val(dayd + '-' + monthd + '-' + yeard);
}
if(arrivalDate < departureDate) {
var arrDate = arrivalDate;
arrDate.setDate(arrDate.getDate() + 1);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
$("#Departure").val(day + '-' + month + '-' + year);
}
}
this condition not related with the validation that i want this is to
set departureDate +1 after arrival date on change
if (arrivalDate >= departureDate)
this condition not related with the validation that i want this is to
set departureDate +1 after arrival date on change
if(arrivalDate < departureDate)
this condition i make it for this validation but didn't work
if (timeDiff > 1)

Instead of using the getDate() method to calculate the timeDiff, use getTime() and do a simple subtraction, followed by a millisecond-to-days refactoring.
Something like this:
var startDate = $("#Arrival").val().split("-");
var endDate = $("#Departure").val().split("-");
var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
var timeDiff = Math.abs(departureDate.getTime() - arrivalDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
Additionally, while subtracting Date type values, the getTime() method becomes optional and a direct subtraction departureDate - arrivalDate can also be done.

If you're using datejs, creating a TimeSpan will help here.
var sync = function () {
var val1 = $("#Arrival").val();
var val2 = $("#Departure").val();
var startDate = Date.parseExact(val1, "ddMMMyy");
var endDate = Date.parseExact(val2, "ddMMMyy");
var diff = new TimeSpan(endDate - startDate);
var newEndDate = startDate.add(diff.days).days();
$("#Departure").val(newEndDate.toString("ddMMyyy"));
};
You could trigger this function to automatically fire by wiring up a change listener on the startDate input field. Just a thought.
Hope this helps.

To do this you need to remember either the arrival date before it was modified, or the number of days between arrival and departure dates. That way you can adjust the departure date by whatever amount the arrival date moved by.
You can store the "old" arrival date in lots of places, the defaultValue might be a good place. So when arrival date is updated, compare the new arrival date to the old one, set the old do the new one and adjust the departure date accordingly, e.g.
// Some helper functions
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
function formatDate(date) {
if (isNaN(date)) return date.toString();
function z(n){return (n<10?'0':'')+n}
return z(date.getDate()) + '-' +
z(date.getMonth()+1) + '-' +
date.getFullYear();
}
function arrivalChange() {
// Check value entered is valid, if so,
// make sure formatted correctly
var arrDate = parseDMY(this.value);
// Deal with invalid input
if (isNaN(arrDate)) {
this.value = "Invalid date";
this.focus();
return;
}
// Tidy formatting
this.value = formatDate(arrDate);
var daysDiff, depDate;
var depEl = this.form.departureDate;
// Get number of days shifted and move departure date accordingly
daysDiff = Math.round((arrDate - parseDMY(this.defaultValue)) / 8.64e7);
this.defaultValue = this.value;
depDate = parseDMY(this.form.departureDate.defaultValue);
depDate.setDate(depDate.getDate() + daysDiff);
this.form.departureDate.value = formatDate(depDate);
this.form.departureDate.defaultValue = formatDate(depDate);
}
function departureChange(){
// Check value entered is valid, if so,
// make sure formatted correctly
var depDate = parseDMY(this.value);
if (isNaN(depDate)) {
this.value = 'Invalid date';
this.focus();
} else {
this.value = formatDate(depDate);
this.defaultValue = formatDate(depDate);
}
}
// Set dates in inputs, attach listeners
window.onload = function() {
var form = document.forms[0];
var now = new Date();
form.arrivalDate.value = formatDate(now);
form.arrivalDate.defaultValue = form.arrivalDate.value;
now.setDate(now.getDate() + 1);
form.departureDate.value = formatDate(now);
form.departureDate.defaultValue = form.departureDate.value;
form.arrivalDate.addEventListener('change', arrivalChange, false);
form.departureDate.addEventListener('change', departureChange, false);
};
<form onsubmit="return false;">
Arrival date (dd-mm-yyy): <input name="arrivalDate"><br>
Departure date (dd-mm-yyy): <input name="departureDate"><br>
<input type="reset">
</form>
If the user enters an invalid date at any time, pressing reset should get back the previous values.

Related

convert only time String to Timestamp

So what I have is a time string which shows the time as h:m:s.ms
But the problem is that I want to covert them to timestamp values it shows NaN values.
I am using Date.parse() to convert the time into timestamp.
Here is the code that I have tried.
var date;
function myFunction() {
var d = new Date();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var maindate = h + ":" + m + ":" + s + "." + ms ;
var datestring = Date.parse(maindate)
var data = Math.random(0,1);
console.log("Date : ", maindate) ;
console.log("Data : ", data);
}
myFunction();
You can see the date and data in the console window.
the date variable here shows NaN Value.
Please tell me what I am doing wrong.
If you want a timestamp you need a full time with day, month and year
var date;
function myFunction() {
var d = new Date();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var day = d.getDate();
var month = d.getMonth() + 1; // getMonth returns an integer between 0 and 11
var year = d.getFullYear();
var maindate = `${day}-${month}-${year} ${h}:${m}:${s}.${ms}`;
var datestring = Date.parse(maindate)
console.log("Data : ", datestring);
}
myFunction();
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
You could also use a regular expression with capturing groups to parse the date string in one line.
var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]
As I want to get the timestamp in result. I got my sholution of the above question that I posted
Here is the Final code which is giving me the expected result.
function addZero(x,n) {
while (x.toString().length < n) {
x = "0" + x;
}
return x;
}
var date;
function myFunction() {
var d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1; // Since getMonth() returns month from 0-11 not 1-12
var year = d.getFullYear();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var maindate = year +"-" + day + "-" + month +" "+ h + ":" + m + ":" + s + "." + ms ;
var datestring = Date.parse(maindate)
var data = Math.random(0,1);
console.log("Date : ", datestring) ;
console.log("Data : ", data);
}
myFunction();
I had to include the day month and year value also. WHich I updated in the Answer. rest of the code works fine.
For this, you don't need your addZero() function any more and it's unnecessary to delacre var date; globally.
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var ms = d.getMilliseconds();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var maindate = day + '-' + month + '-' + year + ' ' + h + ':' + m + ':' + s + '.' + ms;
var datestring = Date.parse(maindate);
console.log("Data : ", datestring);
Take a look at momentjs.com, maybe this could be a clean and simple solution for you too - depending on your environment.

Generating series of dates between two given date with simplified method [duplicate]

This question already has answers here:
Javascript - get array of dates between 2 dates
(31 answers)
Closed 3 years ago.
I need to generate the series of all dates between two given dates. How ever I am not able to get desire output.
I tried using the below code. I gt an empty array.
function getDates(startDate, endDate) {
var dates = [];
var currentDate = new Date(startDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate = currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
};
When I execute console.log(getDates("2019-10-10","2019-11-20")), I get the result as empty array. I didn't get the series of dates as a result.
As mentioned by #RobG, parsing date can yield different results hence consider using the following:
function parseDate(input) {
var parts = input.split('-');
return new Date(parts[0], parts[1] - 1, parts[2]);
}
function getDates(startDate, endDate) {
var dates = [];
var currentDate = parseDate(startDate);
endDate = parseDate(endDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
}
console.log(getDates("2019-10-10", "2019-11-20"));
Original Answer:
You could change endDate into Date type and not set currentDate as setDate is doing it for you:
function getDates(startDate, endDate) {
var dates = [];
var currentDate = new Date(startDate);
endDate = new Date(endDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
}
console.log(getDates("2019-10-10", "2019-11-20"));
You have to call new Date() on line 8.
function getDates(startDate, endDate) {
const dates = [];
let currentDate = new Date(startDate);
while (currentDate <= new Date(endDate)) {
const final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1))
}
return dates;
};
const dates = getDates("2019-01-01", "2019-10-01");
console.log(dates);
As others have said, you're comparing a string and a Date, so things go awry.
ISO 8601 format dates can be compared as strings without being parsed to Dates. Timestamps in the format YYY-MM-DD are parsed as UTC, so you need to be careful with manipulating them. In the OP, the strings are parsed as UTC but local methods are used to format the timestamps, so they may be out by 1 day for users west of Greenwich.
One option is to use UTC methods for incrementing the date and to create strings for comparison, e.g.
// startDate, endDate in format YYYY-MM-DD
function getDates(startDate, endDate) {
let toISODate = date => date.toISOString().substr(0,10);
var dates = [];
var currentDate = new Date(startDate);
while (startDate <= endDate) {
dates.push(startDate);
currentDate.setUTCDate(currentDate.getUTCDate() + 1);
startDate = toISODate(currentDate);
}
return dates;
};
console.log(getDates('2019-09-01', '2019-10-01'));
Use a library like moment.js for date manipulation. These functions are readily available in these.
window['moment-range'].extendMoment(moment);
const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));
console.log(Array.from(range.by('day')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>
And this question has lot of other methods as answers - from which I copied the above solution.

Javascript increment and decrement YYYY-MM-DD by 1 day

I got this from another stack question
incr_date(date_str){
let parts = date_str.split("-");
let dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month (starts with 0)
parseInt(parts[2], 10) // date
);
dt.setDate(dt.getDate() + 1);
parts[0] = "" + dt.getFullYear();
parts[1] = "" + (dt.getMonth() + 1);
if (parts[1].length < 2) {
parts[1] = "0" + parts[1];
}
parts[2] = "" + dt.getDate();
if (parts[2].length < 2) {
parts[2] = "0" + parts[2];
}
return parts.join("-");
}
It works but how can I convert this function to decrement the date instead of increment?
I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js
function dateAdd(dte){
var date = new Date(dte);
date.setDate(date.getDate() + 1);
console.log("add one day= "+date)
}
function datesub(dte){
var date = new Date(dte);
date.setDate(date.getDate() - 1);
console.log("minus one day = "+ date)
}
dateAdd("01-01-2017")
datesub("01-01-2017")
I'd convert the string to Javascript understandable format, increment a day and convert it back to user understandable format. I'm using the flag(Boolean) to determine weather to Increment the date and vice versa.
var convertDate = function(dt, flag) {
var dateArr = dt.split('-');
var tempDate = new Date();
var mm = dateArr[1] - 1; //Javascript considers 0 as Jan
tempDate.setFullYear(dateArr[0]);
tempDate.setMonth(mm);
tempDate.setDate(dateArr[2]);
if (flag) {
tempDate.setDate(tempDate.getDate(dateArr[2]) + 1);//Add's one day
} else {
tempDate.setDate(tempDate.getDate(dateArr[2]) - 1);//Sub's one day
}
var userFriendlyMonth = (Number(tempDate.getMonth()) + 1); //user considers 1 as Jan
return tempDate.getFullYear() + '-' + userFriendlyMonth + '-' + tempDate.getDate();
}
document.getElementById("increment").innerHTML = convertDate('2018-11-30', true);
document.getElementById("decrement").innerHTML = convertDate('2018-11-30', false);
<div>Increment: <span id="increment"></span></div>
<div>Decrement: <span id="decrement"></span></div>

Not getting date format using javascript

I want to get all dates in between 2 dates. So here I have mentioned statdate is date and end date is weekdate. In between 2 dates I want all dates.
Actully I am getting all dates But Not proper Format ,what i want in this format DD/MM/YY.
Now I am Getting in default Format (Sat Jun 09 2007 17:46:21)
$(document).ready(function () {
$("#day").click(function () {
startJsonSession();
return false;
});
function startJsonSession() {
var inputdate = $('#inputdate').val();
//alert("Input Date!!!" + inputdate );
var d = new Date(inputdate);
var nowMS = d.getTime(); // get # milliseconds for today
//alert(nowMS);
var week = 1000 * 60 * 60 * 24 * 7; // milliseconds in one week
//alert(week);
var oneWeekFromNow = new Date(nowMS + week);
//alert("oneWeekFromNow!!!" + oneWeekFromNow);
var fromdate = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (fromdate < 10) {
fromdate = "0" + fromdate;
}
if (month < 10) {
month = "0" + month;
}
//var date = fromdate + "/" + month + "/" + year;
var date = year + "/" + month + "/" + fromdate;
alert("InputDate!!!!" + date);
//var weekdate=oneWeekFromNow.getDate() + "/" + month + "/" + year;
var weekdate = year + "/" + month + "/" + oneWeekFromNow.getDate();
alert("weekdate!!!" + weekdate);
var tomorrow = new Date(d.getTime() + (24 * 60 * 60 * 1000));
var tomorrowdate = tomorrow.getDate();
var month1 = tomorrow.getMonth() + 1;
var year1 = tomorrow.getFullYear();
if (tomorrowdate < 10) {
tomorrowdate = "0" + tomorrowdate;
}
if (month1 < 10) {
month1 = "0" + month1;
}
//var nextday = tomorrowdate + "/" + month1 + "/" + year1;
var nextday = year1 + "/" + month1 + "/" + tomorrowdate;
alert("tomorrow!!!!" + nextday);
var d1 = new Date(date);
alert("D1!!!!!" + d1.);
var d2 = new Date(weekdate);
var aDates = [];
do {
aDates.push(d1.toString());
d1.setDate(d1.getDate() + 1);
}
while (d1 <= d2);
alert("Dates!!!" + aDates);
//alert(aDates.join("\n"));
}
});
You can do it in this way
$("#getDate").click(function () {
var start = $("#startdate").datepicker("getDate"),
end = $("#enddate").datepicker("getDate");
currentDate = new Date(start),
between = [];
while (currentDate < end) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
for (var i = 0; i < between.length; i++) {
var date = $.datepicker.formatDate('dd/mm/yy', new Date(between[i]));
between[i] = date;
}
console.log(between)
})
Here 'between' is the array which contains all your required Date
SEE DEMO HERE
alert("Dates!!!" + aDates.getDate()+"/"+ (aDates.getMonth()+1)+"/"+ aDates.getFullYear());
You seem to want to get a array of date strings in d/m/y format given an input string in the same format. The following functions will do that.
// Parse a string in dmy format
// return a date object, NaN or undefined
function parseDMY(s) {
var b = s.match(/\d+/g);
if (b) {
return new Date(b[2], --b[1], b[0]);
}
}
// Given a date object, return a string in dd/mm/yyyy format
function formatDMY(date) {
function z(n){return (n<10? '0' : '') + n;}
return z(date.getDate()) + '/' + z(date.getMonth() + 1) + '/' + date.getFullYear();
}
function getWeekDates(s) {
var d = parseDMY(s);
var dates = [];
if (d) {
for (var i=0; i<7; i++) {
dates.push(formatDMY(d));
d.setDate(d.getDate() + 1);
}
return dates;
}
}
console.log(getWeekDates('7/7/2014').join());
// 07/07/2014,08/07/2014,09/07/2014,10/07/2014,11/07/2014,12/07/2014,13/07/2014
Note that adding 1 day to a date is preferred over adding milliseconds as it allows the Date object to take account of daylight saving changes that might be involved.

JavaScript add day(s)

How to add a day (or 2 days) to date 31.07.2012 and return result in format dd.MM.yyyy (same format as input date)?
The best way would be to use the javascript date object. The date object in javascirpt is initialized as mm/dd/yyyy or as Date(year,month-1, date). That is,
dateString = "31.07.2012"
dateSplit = dateString.split('.')
date = new Date(dateSplit[2], dateSplit[1]-1, dateSplit[0])
date.setDate(date.getDate()+2)
newDateString = ((date.getDate() > 10) ? date.getDate() : ("0" + date.getDate())) + "." + ((date.getMonth()+1 > 10) ? date.getMonth()+1 : ("0" + (date.getMonth()+1))) + "." + (date.getFullYear())
month-1 is used in Date(year,month-1, date) because months start with 0
The result will be
"02.08.2012"
var numDaysToAdd = 2;
var inputDateString = "31.07.2012";
var resultDate = stringToDate(inputDateString);
resultDate.setDate( resultDate.getDate()+numDaysToAdd );
var result = dateToString( resultDate );
alert(result);
function stringToDate( aString )
{
var dateArray = aString.split(".");
return new Date(dateArray[2],dateArray[1]-1,dateArray[0]);
}
function dateToString( aDate )
{
var date = aDate.getDate();
date = (date > 9) ? date : "0"+date.toString();
var month = aDate.getMonth()+1;
month = (month > 9) ? month : "0"+month.toString();
var year = aDate.getFullYear();
return (date+"."+month+"."+year);
}
/**
* Format date (2012.08.31)
*/
Date.prototype.format = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '.' + (mm[1]?mm:"0"+mm[0]) + '.' + (dd[1]?dd:"0"+dd[0]); // padding
}
/**
* Increase current time
*/
Date.prototype.increase_days = function(days) {
this.setTime(this.getTime() + (days * (1000 * 60 * 60 * 24)));
return this;
}
//usage:
var date = new Date();
date.increase_days(2);
console.log(date.format());
assuming inputDateString format is dd.mm.yyyy
function addDaysToDate (inputDateString ,noOfDays ){
var myDate=dateString.split(".");
var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
var dateInMilliSec = new Date(newDate).getTime();
var addDaysToTime = new Date(dateInMilliSec + (86400000 * noOfDays));
var dd = addDaysToTime.getDate();
var MM = addDaysToTime.getMonth()+1;
var yyyy = addDaysToTime.getFullYear();
return dd+"."+MM+"."+yyyy;
};
This will do it for you
var d = "31.07.2012";
d = d.split(".");
date = new Date(d[2],d[1]-1,d[0]);
date.setDate(date.getDate() + 2);
document.body.innerHTML += (date.getDate() + "." + date.getMonth() + "." + (date.getFullYear()));

Categories