JavaScript Date UTC datetime-local - javascript

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.

Related

Calculate all dates in between given start and end date using 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;
}

How to compare date and time in two separated fields with actual date-time (by JavaScript)?

How by Javascript compare date and time in two datetimepicker fields with actual datetime? In other words I need to consider if date and time in my form is after or before Now.
I have two datetimepicker fields in my form:
(I am using datetimepicker on http://xdsoft.net/jqplugins/datetimepicker/)
Really not elegant way would be somethink like:
var dateVal = $('#dtpckr-StartMainDateTime-Date').val();
var timeVal = $('#dtpckr-StartMainDateTime-Time').val();
var day = dateVal.toString().substr(0, 2);
var month = dateVal.toString().substr(3, 2);
var year = dateVal.toString().substr(6, 4);
var hour = '00';
var minute = '00';
if (timeVal) {
hour = timeVal.toString().substr(0, 2);
minute = timeVal.toString().substr(3, 2);
}
var startDate = new Date(year, month - 1, day, hour, minute);
var now = new Date();
if (startDate > now) {
console.log('future');
}
else {
console.log('current or past');
}
Convert your dateTime into millisec
getCurrentMillis() and check if its greater, if so then its the end date validation. If its happening for start date then its an error and vizversa validation.
Hope you understood.

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

Javascript simple code error

Can't seem to find the problem. Every time I run it I get NaN for ageDale, been looking at it for a while now, its probably simple but I appreciate the help!
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
<input type="text" id="birthDate">
Current Date
<input type="text" id="currentDate">
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
<script>
function test() {
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
alert(ageDale)
}
</script>
Also, is it necessary for me to have that else statement? or is there another way to set up this so its not needed?
This
ageDate.value
should be
ageDate
only. It's a variable and already contains only the difference from
birthDate.value - currentDate.value
if(ageDate.value < 1) {
// ^ here
(ageDale = ageDate.value * -1)
} //^ here
else {
(ageDale = ageDate.value * 1)
// ^ and here
You only need to fetch the value when getting data from, for example, input fields.
Also (depending on how you input them) it might be a problem to calculate dates. For debugging purposes you should
console.log()
your variable values, that way you will find out quickly where the error is.
A good place for a console.log() in your code would be, for example after this block:
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
console.log(ageDate);
SIDENOTE:
You might want to take a look at moment.js, which will help you with date calculations. For example, you can get differences between dates with moment.js like this:
var a = moment([2014, 12, 05]);
var b = moment([2014, 12, 06]);
a.diff(b, 'days') // 1
Try this:
var btn = document.getElementById("Submit_Button");
btn.onclick = function test() {
var birthDate = parseInt(document.getElementById("birthDate").value);
var currentDate = parseInt(document.getElementById("currentDate").value);
var ageDate = (birthDate - currentDate);
if(ageDate < 1) {
(ageDate = ageDate * -1)
}
else {
(ageDate = ageDate * 1)
}
alert(ageDate)
}
As baao said, you have spelling errors. After correcting those, you want to consider what your input is going to be, and make sure you are checking that the input is valid.
For example, if I type "September 10th" for my birthday and "December 10th" for the current date, your function will try and subtract two strings which is not valid. If you're going to use a custom input field for the date, you need to be sure its in a consistent and parseable format.
I'd recommend asking for just their birthday in a specific format and parsing it from there, since we can use Javascript to get the current date easily. For example, mm-dd-yy. We may re-write it as:
function test() {
//lets get the date, in the format 'mm-dd-yy'. You'd want to do error checking at some point if you're serious about it
var dateInput = document.getElementById("birthDate").value;
//get each individal date type by splitting them at the -, giving ['dd', 'mm', 'yy']
var dateSplit = dateInput.split('-');
//create a Javascript date object with the date we got
var birthDate = new Date(dateSplit[2], dateSplit[0], dateSplit[1]);
//create another with the current date and time
var currentDate = new Date();
// find the difference in milliseconds
var dateDifference = Math.abs(birthDate.getTime() - currentDate.getTime());
// convert to years
var age = dateDifference / (1000 * 3600 * 24 * 365);
alert(age);
}
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
Birth Date (dd-mm-yy):
<br>
<input type="text" id="birthDate">
<br>
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
just modify this code
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
with this
var vbirthdate = new Date(document.getElementById("birthDate").value);
var vcurrentdate = new Date(document.getElementById("currentDate").value);
var ageDate = Math.floor((vbirthdate-vcurrentdate)/(1000*60*60*24));
if(ageDate < 1) {
(ageDate = ageDate * -1)
} // no need to do something like this (ageDate *1) if it is already a positive number, just check if it's a negative then convert it to a positive number
you can try the code at http://jsfiddle.net/kapasaja/duco4cqa/5/
what you asking is similar to this post

How to change a particular value when I select a date?

The requirement is I have two date fields:
One is effective date and date of birth. When I select the effective date on the page.
The age field should do the following calculation.
That is age would be Effective date - date of birth. the result should be set to the age field.
How to do in javascript or JQuery?
I'm using tapestry front end. So in the HTML page I want to do this setting of value to age field.
You need to convert your dates into milliseconds and subtract them, then calculate the age.
HTML
<input type="date" id="effective" />
<input type="date" id="born" />
jQuery
function getTime(date){
var dateArr = date.split('-');
return new Date(dateArr[0], dateArr[1], dateArr[2]).getTime();
}
function calcDate(date1,date2) {
var eff_date = getTime(date1);
var born_date = getTime(date2);
var diff = Math.floor(eff_date - born_date);
var day = 1000* 60 * 60 * 24;
var days = Math.floor(diff/day);
var months = Math.floor(days/31);
var years = Math.floor(months/12);
return years
}
$("input[type=date]").change(function(){
if($("#effective").val() != "" && $("#born").val() != ""){
var age = calcDate($("#effective").val(),$("#born").val())
alert(age);
}
});
Check out this Fiddle..

Categories

Resources