Trying to set datetime-local using JavaScript - javascript

I am using the following code at this codepen to try to populate a datetime-local input element with today's data and time. What they have on this tutorial does not work. I also tried what is in this SO post but also does not seem to work. How do can I set the datetime to today's date and time into a datetime-local input element. Thank you.
HTML:
<input type="datetime-local" id="datetime" name="datetime">
JS:
let today = new Date().toISOString();
document.getElementById('datetime').value = today;
console.log(today);

You may try this:
let today = new Date();
today.setMinutes(today.getMinutes() - today.getTimezoneOffset());
document.getElementById('datetime').value = today.toISOString().slice(0, -1);
console.log(today);
<input type="datetime-local" id="datetime" name="datetime">

Try this. It's the example used on MDN:
const today = new Date().toISOString();
const dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = today;

Try this code.
Number.prototype.AddZero= function(b,c){
var l= (String(b|| 10).length - String(this).length)+1;
return l> 0? new Array(l).join(c|| '0')+this : this;
}//to add zero to less than 10,
var d = new Date(),
localDateTime= [(d.getMonth()+1).AddZero(),
d.getDate().AddZero(),
d.getFullYear()].join('/') +', ' +
[d.getHours().AddZero(),
d.getMinutes().AddZero()].join(':');
var elem=document.getElementById("LocalDate");
elem.value = localDateTime;
<input type="datetime-local" name="name" id="LocalDate">

Related

Limit the date to today and block the previous dates

I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.
Compare two dates with JavaScript
I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.
For information, I am obliged to use JavaScript to handle the dates.
function validation()
{
const date_start = document.getElementById('date_start').value;
const inputDate = new Date(date_start);
const dayFromImputDate = inputDate.getFullYear(); // previous day
const now = new Date();
const dateNow = now.getFullYear();
if(dayFromImputDatee < dateNow) {
document.getElementById('date_startError').innerHTML = " ** Error date ! ";
return false;
}
if(date_start == ""){
document.getElementById('date_startError').innerHTML = " ** date empty ! ";
return false;
}
console.log("Date is valid");
return true;
}
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
</body>
</html>
Thank you very much for your help and your time.
You can check if input date is less than today's date using < operator
const form = document.querySelector('form');
const error = document.getElementById('date_startError');
function validation(event) {
event.preventDefault();
const startDate = form.elements['date_start'].value;
if (!startDate) {
error.innerHTML = " ** date empty ! ";
return;
}
const inputDate = new Date(startDate).getDate();
const today = new Date().getDate();
if (inputDate < today || !inputDate.valueOf()) {
error.innerHTML = " ** Error date ! ";
return;
}
error.innerHTML = "date is valid";
}
<form action="#" onsubmit="validation(event)">
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
Because HTML5 already has min and max attributes for the date input type, you don't need to implement a separate validation function to accomplish this. Here is a simpler way:
var date = new Date();
var iso_date = date.toISOString().substring(0, 10);
document.getElementById("date_start").setAttribute('min', iso_date);
Basically, you just get a new Date() object, extract and format it into an ISO 8601 date format, and set it into the min attribute. This also limits the browser selection calendar to future dates only.
If I understand the problem correctly you are trying to restrict a date form input to the current day or some future date.
To check whether a date is valid you could do this:
let earliestPossibleDate = new Date(
now.getFullYear(), now.getMonth(), now.getDate()
);
let isValidDate = date_start >= earliestPossibleDate
Three things:
You need to get your Current Date and set time to start of day.
You need to get your Selected Date and set time to start of day
Compare whether Selected Date is Greater or Equal to the Current Date.
Note that when you compare dates, you need to also consider the time.
Most calendar tools, include the time as a response to the selected date. You need to be aware of that.
This doesn't include other date validations. This will only solve the current problem at hand. Hope this helps! =)
const isValidDate = (selectedDate) => {
const currentDate = new Date();
// reset to start of day
currentDate.setHours(0);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
currentDate.setMilliseconds(0);
const newDate = new Date(selectedDate);
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
return newDate.getTime() >= currentDate.getTime();
}
To use, simply throw the selected date in the function. Should return true if the date is greater or equal to the date today.
isValidDate(selectedDateFromDatePicker);

Add one day to date string in javascript

I am setting the min of checkOut as the value of checkIn. My problem comes that i need to add one day to firstdate. (Should not be able to check out on or before the check in day.)
<script>
function updatedate() {
var firstdate = document.getElementById("checkIn").value;
document.getElementById("checkOut").value = "";
document.getElementById("checkOut").setAttribute("min",firstdate);
}
</script>
Check In
<input type="date" id="checkIn" onchange="updatedate();" name="checkin">
Check out
<input type="date" id="checkOut" min="" name="checkout">
It's sort of do-able but it only works in Chrome since that's the only browser that supports a date input at the moment. Oh, and this solution uses momentjs because parsing a date and correctly adding 1 day to it is way harder that it sounds.
function updatedate() {
var checkin = document.getElementById("checkIn").value;
checkin = moment(checkin);
var checkout = checkin.add(1, 'd');
document.getElementById("checkOut").setAttribute("min", checkout.format('YYYY-MM-DD'));
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div class="container">
Check In
<input type="date" id="checkIn" onchange="updatedate();" name="checkin">Check out
<input type="date" id="checkOut" min="" name="checkout">
</div>
A momentless solution is to parse the checkinDate into a JS date and and then create a new date whilst adding one day to the checkinDate. Though yeah, momentJS is the goto library when dealing with dates.
JSfiddle here:
https://jsfiddle.net/xugajae5/
There was a bit of a hack in getting the min format that the input expected:
var checkoutDateFormat = checkoutDate.toISOString().split('T')[0];
Not all browsers in use support input type date, so you'll need to deal with that to start with.
Then, you can convert the value of firstdate to a Date object, add a day, then get back a date in the required format. Your issue however is that the value of the date input (which is an ISO 8601 format date string) is treated as local, but the Date constructor will treat it as UTC.
So you need to parse the string as a local date, then add the day, then get back a string in the right format. The code below is just an example, you may wish to use a library for the date manipulation. Just remember not to parse the date string with the Date constructor.
function getTomorrow(el) {
var form = el.form;
var start = parseISOAsLocal(form.start.value);
// Check if input date was valid
if (!start.getTime()) {
form.tomorrow.value = '';
form.start.value = 'Invalid date';
return;
}
start.setDate(start.getDate() + 1);
form.tomorrow.value = formatISODate(start);
}
function parseISOAsLocal(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
function formatISODate(date) {
return ('000' + date.getFullYear()).slice(-4) + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2);
}
<form>
Start (yyyy-mm-dd):
<input type="date" name="start" value="2016-08-31"><br>
Tomorrow: <input type="date" name="tomorrow" readonly><br>
<input type="button" onclick="getTomorrow(this)"
value="Show tomorrow">
</form>
<script>
function updatedate(){
var checkInValue = document.getElementById("checkIn").value;
var checkInDate = Date.parse(checkInValue);
var minDate = new Date(checkInDate + 24 * 3600 * 1000);
document.getElementById("checkOut").setAttribute("min", minDate.toDateString());
}
</script>

How to compare two dates in yy-dd-mm format in JavaScript?

I have a form element of date type:
<input type="date" class="form-control" name="InputDOB" id="DOB"
placeholder="DOB" onblur="dateValidate()" required>
The JavaScript code is here:
function dateValidate(){
var date=new Date();
var pass1 = document.getElementById("DOB");
alert(pass1.value);
var date = new Date();
today=date.getFullYear()+'-'+(date.getMonth() + 1)+'-'+date.getDate();
if(pass1.value<today){
alert("date is correct ");
}
}
You don't need today, just change your if to
if(new Date(pass1.value)< date){
alert("date is correct ");
}
//OR
if(new Date(pass1.value)< new Date()){
alert("date is correct ");
}
Based on the code that you've posted, this is how you do it :
html:
<input type="date" class="form-control" name="InputDOB" id="DOB" placeholder="DOB" required>
application.js file that you should load into your HTML file and I'm also using JQuery to accomplish this so you should load it too.
$(document).ready(function () {
$("#DOB").on("blur", function () {
var date=new Date();
var pass1 = document.getElementById("DOB");
alert(pass1.value);
today=date.getFullYear()+'-'+(date.getMonth() + 1)+'-'+date.getDate();
alert(today);
if(pass1.value<today){
alert("date is correct ");
}
})
});
DEMO:
http://fiddle.jshell.net/a2fjzqzw/
I always use moment.js with JavaScript when messing with dates. It mitigates most if not all the hardship when manipulating dates in JavaScript and is a brilliant library.
http://momentjs.com/docs/#/displaying/difference/
The difference method may get you where you need, if not I'm sure you can find a solution in the API.
you need to use getTime(); to compare two dates like
function dateValidate(){
var input = document.getElementById("DOB");
alert(input.value);
var inputDate = new Date(input.value).getTime();
var today = new Date().getTime();
if(inputDate<today){
alert("date is correct");
}
}
Demo

Combining Date and Time input strings as a Date object

I have two input tags for picking date and time from user.
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
These two values are passed to a function where I want to combine these two input values as a Date object:
new Date(y, m, d, hh, mm, a)
Which I can then use to plot an event's details in a Calendar. How can I combine these two values? I have tried:
start:new Date(sdate + stime)
start:new Date(sdate , stime)
start: new Date(sdate.getFullYear() + sdate.getMonth() + sdate.getDate() + stime.getHours + stime.getMinutes())
But none of what I have tried is working.
How do I achieve this when using AngularJS?
In angular it would go something like this:
Controller:
function exampleController($scope) {
$scope.title = "$Watch sample";
$scope.$watch('sdate', function() {
tryCombineDateTime();
});
$scope.$watch('stime', function() {
tryCombineDateTime();
});
function tryCombineDateTime() {
if($scope.sdate && $scope.stime) {
var dateParts = $scope.sdate.split('-');
var timeParts = $scope.stime.split(':');
if(dateParts && timeParts) {
dateParts[1] -= 1;
$scope.fullDate = new Date(Date.UTC.apply(undefined,dateParts.concat(timeParts))).toISOString();
}
}
}
}
HTML
<div ng-app ng-controller="exampleController">
<h2>{{title}}</h2>
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
{{fullDate}}
</div>
You need to make use of the $watch listener on a variable when it changes, then call your function.
Note: it would be even better if you make a directive for this.
Fidle
A very naive approach to combine these two is to split date-components and time-components and make a string. Then make a new Date object using this string.
Input is taken from here:
<p>Start Date</p><p> <input ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input ng-model="stime" type="time" ></p>
Then in script part, split date and time components as follows:
var dd = new Date(sdate).getDate();
var mm = new Date(sdate).getMonth()+1;
var yy = new Date(sdate).getFullYear();
var hh = new Date(stime).getHours();
var ms = new Date(stime).getMinutes();
Then Combine these components to form a string as required(in Calendar):
var x = yy + ',' + mm + ',' + dd + ' ' + hh + ':' + ms;
Now create a new Date object:
var finaldate = new Date(x);
You could do something like this, though this doesn't have anything to do with AngularJS and I can't test on older browsers. I am assuming that you are entering date/time as UTC and I am using Date to create an ISO8601 timestamp as an output. Also assumes that you are using a modern browser that supports HTML5 and ECMA5, otherwise you will need to modify the code.
HTML
<p>Start Date</p><p> <input id="myDate" ng-model="sdate" type="date" ></p>
<p>Start Time</p><p> <input id="myTime" ng-model="stime" type="time" ></p>
<div id="myIso"></div>
Javasceipt
var myIso = document.getElementById('myIso'),
dateParts,
timeParts;
function joinPartsAsDate() {
if (dateParts && dateParts.length === 3 && timeParts && timeParts.length === 2) {
// dateParts[1] -= 1; could be done here
myIso.textContent = new Date(Date.UTC.apply(undefined, dateParts.concat(timeParts))).toISOString();
} else {
myIso.textContent = '';
}
}
document.getElementById('myDate').addEventListener('change', function (e) {
dateParts = e.target.value.split('-');
if (dateParts[1]) { // this could be done in joinPartsAsDate, here for clarity
dateParts[1] -= 1;
}
joinPartsAsDate();
}, false);
document.getElementById('myTime').addEventListener('change', function (e) {
timeParts = e.target.value.split(':');
joinPartsAsDate();
}, false);
On jsFiddle
After testing all stuff described here, i found a very simple solution.
In my view i have
<input type="date" ng-model="tsc.untilDate">
<input type="time" ng-model="tsc.untilTime">
In my Angular Controller both model elements are objects from type Date by default.
With input type="date" the time of this Date object is always 00:00.
With input type="time" the date part of the Date object ist allways set to today.
So i just read the daytime (if it is set) of the TimeDate Object and set it on the DateObject.
if(tsc.untilTime)
{
tsc.untilDate.setHours(tsc.untilTime.getHours());
tsc.untilDate.setMinutes(tsc.untilTime.getMinutes());
}
For those looking for a compact version install the momentjs library.
npm install moment --save
Add it to your file header.
import * as moment from 'moment';
Then just compose the dateTime object with the fluent interface.
let dateTime = moment(this.sdate)
.startOf('day')
.set('hour', this.sTime.getHours())
.set('minute', this.sTime.getMinutes() )
.toDate();
Try this
const timeAndDate = moment(this.sdate + ' ' + this.sTime.getHours() + ' ' + this.sTime.getMinutes());
console.log(timeAndDate.toDate());

how to set date from javascript to html <input type="date"/> element

can anyone please tell me how to set date from javascript to HTML element, Is it possible to do this because it is working with tag but not with tag ,
actually I have a requirement where I want a user to choose a date from one input element and it will automatically set date in another date input element with a 1-year extension.
For example, if I choose a date from the first input as 02/16/2018 then it should automatically fill another date input as 02/16/2019.
Thanks in advance!
I did it in an other way:
document.getElementById('1').addEventListener('change', function() {
var date1 = document.getElementById('1');
var dateSplit = document.getElementById('1').value.split("-");
dateSplit[0] = parseInt(dateSplit[0]);
dateSplit[0] = dateSplit[0] + 1;
dateSplit[0] = dateSplit[0].toString();
var date2 = document.getElementById('2').value = dateSplit[0] + "-" + dateSplit[1] + "-" + dateSplit[2];
});
<!doctype html>
<html>
<body>
<input type="date" id="1">
<input type="date" id="2">
</body>
</html>
I hope this will help you.
$('#field1').on('change',function(e) {
$('#field2').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" Id="field1"/>
<input type="date" Id="field2"/>
Here is the code
const { format } = dateFns
function getDate() {
var oldDate = document.getElementById("oldDate").value;
var date = new Date(oldDate)
var newDate = new Date(date.getFullYear()+1,date.getMonth(),date.getDay())
document.getElementById("newDate").value = format(newDate, 'YYYY-MM-DD');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.js"></script>
<input type="date" onChange="getDate();" id="oldDate" />
<input type="date" id="newDate" />
You can use https://momentjs.com/ to get the desired date and fill with $('selector').val(newdate) to another date input;

Categories

Resources