Calculate all dates in between given start and end date using javascript - javascript

I have a start-date and end-date and I want to calculate array of dates between these days based on a given duration.
for example,
if start date is 01/01/2015 and end date is 01/06/2015 and if I give duration as 3 months then out put should be:
01/04/2015
01/06/2015
How to achieve this using JavaScript and I need to display it in a form.

If you want to calculate difference between two dates using javascript:
Then,
function dateDiff() {
var dtFrom = document.getElementById('txtFromDate').value;
var dtTo = document.getElementById('txtToDate').value;
var dt1 = new Date(dtFrom);
var dt2 = new Date(dtTo);
var diff = dt2.getTime() - dt1.getTime();
var days = diff/(1000 * 60 * 60 * 24);
alert(dt1 + ", " + dt2);
alert(days);
return false;
}
function isNumeric(val) {
var ret = parseInt(val);
}
HTML:
<label for="txtFromDate">From Date : </label>
<input type="text" id="txtFromDate" name="txtFromDate" size="10" maxlength="10" value="03/25/2013"/><br/>
<label for="txtToDate">To Date : </label>
<input type="text" id="txtToDate" name="txtDate" size="10" maxlength="10" value="03/26/2013"/><br/>
<button id="btnCheck" name="btnCheck" onClick="dateDiff();" type="button">Difference</button>
AFTER EDIT:
Following solution is to get all dates between specified dates.
Working Demo
// using Datepicker value example code
$('#getBetween').on('click', function () {
var start = $("#from").datepicker("getDate"),
end = $("#to").datepicker("getDate");
var between = getDates(start, end);
$('#results').html(between.join('<br> '));
});
// This function doing this work.
function getDates(start, end) {
var datesArray = [];
var startDate = new Date(start);
while (startDate <= end) {
datesArray.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return datesArray;
}

Related

JavaScript Date UTC datetime-local

I have a form where user can set a date and time with input format datetime-local. When the form is submitted an error appears for the start-date "Value must 11:52 AM or earlier". My local time is 13:52. I have to select -2 hours. How can I remove this problem?
The form is limited for the start date to select only today and last 72 hours, same for end time.
<input type="datetime-local" name="start_timestamp" id="start_timestamp" required>
<input type="datetime-local" name="end_timestamp" id="end_timestamp" required>
<script>
//Do not let to select END-TIME and START TIME in the PAST
var today = new Date();
var past = new Date(today.setDate(today.getDate() - 3)).toISOString().slice(0, 16);
var today = new Date().toISOString().slice(0, 16);
document.getElementsByName("start_timestamp")[0].min = past;
document.getElementsByName("start_timestamp")[0].max = today;
</script>
<script>
var today = new Date();
var future = new Date(today.setDate(today.getDate() + 3)).toISOString().slice(0, 16);
var today = new Date().toISOString().slice(0, 16);
document.getElementsByName("end_timestamp")[0].min = today;
document.getElementsByName("end_timestamp")[0].max = future;
</script>
I have an image also:
Your issue is timezone related. Because you're using toISOString to set the input value, it's being set to UTC date and time, not local. So create a function to return the local time in the correct format.
E.g.
// Format date as YYYY-MM-DDTHH:mm in local timezone
// to use to set min and max values for inputs
function toISOLocal(date = new Date()) {
return date.toLocaleString('sv').slice(0,-3).replace(' ','T');
}
/* Initialise date inputs to local dates ± perid in days
* Start is set to "now", end it set to now ± period
* #param {string} startID
* #param {string} endID
* #param {number} period - ±days from start to end
*/
function initialiseDateInputs(startID, endID, period) {
let startEl = document.querySelector('#' + startID);
let endEl = document.querySelector('#' + endID);
// Ensure elements exist
if (!startEl || !endEl) return;
// Create min and max timestamps
let d = new Date();
// Create max with zero'd seconds, milliseconds
let minD = toISOLocal(new Date(d.setSeconds(0,0)));
// Create min ±period days from max
let maxD = toISOLocal(new Date(d.setDate(d.getDate() + period)));
// If period is -ve, swap max and min
if (period < 0) {
[minD, maxD] = [maxD, minD];
}
// Set element attribute values
startEl.setAttribute('max', maxD);
startEl.setAttribute('min', minD);
startEl.setAttribute('value', period < 0? maxD : minD);
endEl.setAttribute('max', maxD);
endEl.setAttribute('min', minD);
endEl.setAttribute('value', period < 0? minD : maxD);
}
// Run when elements should exist
window.onload = () => {
initialiseDateInputs('startDate', 'endDate', +3);
}
.screenTip {
font-family: sans-serif;
color: #bbbbbb;
}
input {
font-size: 150%;
}
<form>
<span class="screenTip">Start date and time, must be within last 3 days</span><br>
<input type="datetime-local" name="startDate" id="startDate" required><br>
<span class="screenTip">End date and time, must be within last 3 days</span><br>
<input type="datetime-local" name="endDate" id="endDate" required><br>
<input type="reset">
</form>
Setting the input value attribute means that if the inputs are in a form and it's reset, they'll return to the min and max values appropriately.

datetime-local different format after selecting

Given is an ionic app with <input type='datetime-local'> inputs which runs on an android system. The problem ist that the inputs have different formats after the user selects a Dates. Start is after the user selected a date and Ende is the default formatting. I already tried to add the min, max and step attribute.
The format without the miliseconds is the preferred one.
The Controller
$scope.event = {};
// Default dates
$scope.event.start = new Date();
$scope.event.end = new Date();
$scope.event.end.setHours($scope.event.start.getHours() + 2);
The HTML Part
<label class="item item-input underlinedInput equal-padding ">
<span class="input-label">Start</span>
<input type="datetime-local" placeholder="Start" ng-model="event.start" step="1" min="1900-01-01T00:01:00" max="2900-01-01T23:59:59">
</label>
<label class="item item-input underlinedInput equal-padding ">
<span class="input-label">Ende</span>
<input type="datetime-local" placeholder="Ende" ng-model="event.end" step="1" min="1900-01-01T00:01:00" max="2900-01-01T23:59:59">
</label>
For anyone interested, i wrote a factory that solves my problem.
Instead of creating a date like $scope.event.start = new Date() just use $scope.event.start = Tools.currentDate();
.factory('Tools', function () {
return {
utcDate: function (date) {
var d = new Date(date.replace(' ', 'T'));
d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
return d;
},
currentDate: function () {
var d = new Date();
var year = d.getFullYear();
var month = this.leadingZero(d.getMonth());
var day = this.leadingZero(d.getDate());
var hour = this.leadingZero(d.getHours());
var minutes = this.leadingZero(d.getMinutes());
return this.utcDate(year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00");
},
leadingZero: function(number){
return ("0"+number).substr(-2,2);
}
}
})
use date object like
$scope.event.start = new Date(2010, 11, 28, 14, 57);
refer this plunker
you can use moment JS and you will have a better control over date manipulation in your app. moment js docs
var startDate = moment().format('DD/MM/YYYY, HH:MM A');
var endDate = moment().add(2, 'hours').format('DD/MM/YYYY, HH:MM A')

Validating time and date in javascript for html form

I've tried many ways to validate the date and time with Javascript functions but none seem to work. I'd like to alert users when their date input is of a past date whereas the time start cannot be the same as time end and it cannot be later than time end.
My HTML codes:
<p>
<label> Date:
<input type="date" id="date" name="date" required />
</label>
</p>
<p>
<label> Time start:
<input type="time" id="timeStart" name="timeStart" required />
</label>
</p>
<p>
<label> Time end:
<input type="time" id="timeEnd" name="timeEnd" required />
</label>
</p>
Javascript I tried:
function valiDate(date) {
var today=new Date();
var inputDate=document.getElementById("date").value;
if (inputDate < today) {
alert("Your event cannot happen in the past.");
}
}
function checkDate(date)
{
var dateInput=document.getElementById("date").value;
var parts=date.split("/");
var yearInput=parts[0];
var monthInput=parts[2];
var dayInput=parts[3];
var minYear = 1902;
var maxYear = (new Date()).getFullYear();
var maxMonth = (new Date()).getMonth();
var currentDay = (new Date()).getDate();
if (yearInput<maxYear || monthInput<maxMonth || dayInput<currentDay ) {
alert("Event cannot be held in the past. Move on.");
}
}
The method used for comparison of dates is wrong.
d1.getTime() === d2.getTime();
d1.getTime() !== d2.getTime();
Use getTime() operator or dates.compare() function.
If you want to split the dates, the use '-' to split them.
Here is a working jsFiddle:
https://jsfiddle.net/BoyWithSilverWings/rc08otjc/
Please try this
function validDate() {
var today=new Date();
var inputDate = new Date(document.getElementById("date").value);
today.setHours(0,0,0,0);
if (inputDate < today) {
alert("Your event cannot happen in the past.");
}
else {
var startTime = TimeinMillisec(document.getElementById("timeStart").value);
var endTime = TimeinMillisec(document.getElementById("timeEnd").value);
if( startTime > endTime)
alert("Event cannot be held");
else
alert("Done");
}
}
function TimeinMillisec(gTime)
{
var parts=gTime.split(" ");
var hhmm = parts[0].split(":");
hhmm[0] = parseInt(hhmm[0]);
if( parts[1].toLowerCase() === "pm")
hhmm[0] = parseInt(hhmm[0]+12);
var seconds = parseInt( ((+hhmm[0]) * 60 * 60) + ((+hhmm[1]) * 60));
return seconds;
}

Javascript: Subtract time with another fixed time

Consider I have following date and time in 24 hours format.
Example
2015/04/02 12:00
2015/03/02 14:00
I have to subtract the above time with 9 hours so that I will get
2015/04/02 -> 3 (hours)
2015/03/02 -> 5 (hours)
HTML
<form name="formName" onsubmit="return checkDate(this)">
<input type="text" value="" name="date1" />
<input type="text" value="" name="date2"/>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
Javascript
function checkDate(theForm)
{
var a = theForm.date1.value;
var b = theForm.date2.value;
var date1 = new Date(a);
var date2 = new Date(b);
var dateStart = new Date();
var dateEnd = new Date();
dateStart.setHours(9);
Start_sec = (date1/ 1000.0) - (dateStart/ 1000.0);
Start_hours = parseInt(Start_sec / 60 / 60);
document.getElementById("demo").innerHTML = Start_hours ;
return false;
}
Try the following code.
function checkDate(theForm)
{
var a = theForm.date1.value;
var b = theForm.date2.value;
var date1 = new Date(a);
var date2 = new Date(b);
date1.setHours(date1.getHours() - 9);
date2.setHours(date2.getHours() - 9);
document.getElementById("demo").innerHTML = "Date 1 : " + date1.toString() + "<br/>Date 2 : " + date2.toString();
return false;
}
If it is acceptable to use third party libraries, then you can achieve this task simply using moment.js. In one line, you can accomplish the task with this code:
moment('2015/04/02 12:00').subtract('hours',9).format('YYYY/MM/DD hh:mm')
//just a number plus the word 'hours'
.format('h [hours]')
//time only
.format('h:mm')
Occasionally I update this fiddle I maintain with more examples: http://jsfiddle.net/JamesWClark/9PAFg/
var date = new Date("2015/04/02 12:00");
var out = new Date(date.getTime() - 32400000); //9*60*60*1000
You can just literally subtract 9 hours directly...:
var t = new Date(2015,2,3,18);
t.setTime(t - 9*60*60*1000); //subtract 9 hours

Convert a String to a Single Date in Javascript

I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle

Categories

Resources