Need to compare new date with datepicker - javascript

Im struggling with dates in javascript. Im going to compare some dates input but the user and the date the user input depends which list the information goes. My issue is comparing the system date and the date picker date. The system date shows the format of 'Tue Dec 22 2015 00:00:00 GMT+0000 (GMT)' date picker shows 22/12/2015. How can i change the system date to match the date picker format so i can compare dates? I want to do it without jQuery(i know date picker goes against this).
Here my code so far for the date which basically is just setting the time to 00:00:00.
var today = new Date();
today.setHours(0,0,0,0);
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0,0,0,0);
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0,0,0,0);
console.log(today);
var dateTask = document.getElementById("date").value;
console.log(dateTask);

You have to parse the user input into a Date object. 22/12/2015 is not a valid datestring for the Date constructor so you have to parse it yourself.
You can do something like this:
var dateSplit= document.getElementById("date").value.split('/'),
dateTask = new Date(dateSplit[2],dateSplit[1]-1,dateSplit[0], 0, 0, 0, 0);
Note: this code is very basic and needs an enhancement when you're parsing real user input.
After that you can compare the dates like this:
today.getTime() === dateTask.getTime()

Just split the string with str.split("/"); and construct Date in one of the ways that is pointed out here.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
be careful months are from 0-11

You don't actually need JQuery if you want a date-picker, but that's beside the point. I think the best approach is to parse the user input as a date using Date.parse. You can then compare them as unix epoch timestamps.
"use strict";
var datePicker = document.querySelector('#date');
datePicker.addEventListener('change',function(){
var udate = Date.parse(this.value);
var sysdate = Date.now();
document.querySelector('#d').innerText = udate;
document.querySelector('#sys').innerText = sysdate;
});
form {
position: relative;
}
label, input, output {
float: left;
}
label {
clear: left;
width: 128px;
}
<form>
<label for="date">user input</label>
<input type="date" name="date" id="date">
<label for="d">user date</label>
<output id="d" name="d" for="date"></output>
<label for="sys">system date</label>
<output id="sys" name="sys"></output>
</form>

const datePicker = document.querySelector("#date");
const todayDate = new Date().toLocaleDateString();
const datePickerValue = new Date(datePicker.value).toLocaleDateString();
datePicker.addEventListener("change", () => {
if (datePickerValue === todayDate) {
alert("");
} else {
alert("");
}
});

Related

html date form: how to set start date as tomorrow using Javascript

Trying to limit the start date as tomorrow (local date). Can someone tell why below code isn't working:
<form method="POST">
<div>
<label for="s2">pickup_date</label>
<input type = 'date' name='pickup_date' required>
<br /><br />
</div>
</form>
<script>
var time = new Date();
var localTimeStr = time.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
today = new Date(localTimeStr)
tomorrow = new Date(today.setDate(today.getDate() + 1)).toISOString().split('T')[0];
t = String(tomorrow)
document.getElementsByName("pickup_date")[0].setAttribute('min', t);
</script>
the output of below code is 2022-01-18:
var time = new Date();
var localTimeStr = time.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
today = new Date(localTimeStr)
tomorrow = new Date(today.setDate(today.getDate() + 1)).toISOString().split('T')[0];
t = tomorrow.split('-')[0]+'-'+tomorrow.split('-')[1]+'-'+tomorrow.split('-')[2]
console.log(t)
however, the calendar start date in the form is still 2022-01-17. But, when I manually set
document.getElementsByName("pickup_date")[0].setAttribute('min', '2022-01-18');
the calendar start from 2022-01-18 correctly. why!
In the OP there is:
var time = new Date();
var localTimeStr = time.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
today = new Date(localTimeStr)
That will return a timestamp with the date and time for Shanghai.
tomorrow = new Date(today.setDate(today.getDate() + 1)).toISOString().split('T')[0];
That will firstly parse the string assigned to today as "local" to the host system using the built–in parser, which it is not required to do by ECMA-262 (see Why does Date.parse give incorrect results?).
It will then return an ISO 8601 formatted string for the equivalent UTC date and time. If the host system's offset is positive, then depending on the time in the timestamp, the date will either be the same day or the previous day. Similarly, for hosts with a negative offset, the date might be the same day or the following day depending on the time in the string and the host system's offset.
There are many questions on formatting dates, the various toLocaleString methods are useful but I don't know how reliable they are in the long term. To get an ISO 8601 formatted local date, the format associated with the language en-CA seems to suit:
new Date().toLocaleDateString('en-CA')
If you want to get timestamps for the current date and tomorrow in Shanghai in YYYY-MM-DD format, consider:
let d = new Date();
let today = d.toLocaleDateString('en-CA', {timeZone:'Asia/Shanghai'});
d.setDate(d.getDate() + 1);
let tomorrow = d.toLocaleDateString('en-CA', {timeZone:'Asia/Shanghai'});
console.log(`Today : ${today}\nTomorrow: ${tomorrow}`);

Only enable during 2 weeks date format html

I have a problem enabling only during 2 weeks data format. For example, I want only to show today and before 14 days. Now my coding just can lock before days.
Scenario:
If today 03 Feb 2021, I want to enable dates are 20 Jan 2021 until 03 Feb 2021. Other dates will be disabled.
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("accident")[0].setAttribute('min', today);
<input type="date" class="form-control" id="accident" name="accident" value="" title="Date of Accident">
Now my result like below the picture:
Hope someone can guide me on which part I am getting wrong it. Thanks.
According to MDN Documentation. You need to set min and max values to specify an interval
// Get date objects
const today = new Date();
const twoWeeksAgo = new Date();
twoWeeksAgo.setDate(today.getDate() - 14);
// Then set in input
const input = document.querySelector('[name=accident]');
input.setAttribute('min', twoWeeksAgo.toISOString().slice(0, 10));
input.setAttribute('max', today.toISOString().slice(0, 10));
<input type="date" name="accident" />
You only set min, but you did not set max.
Because of this relationship, it only knows your minimum date, but does not know your maximum date, so the previous result is normal, as long as you make up the setting, it will work.
For details, please refer to here.
const getDateStr = (d) => d.toISOString().split('T')[0];
const daysRange = (days) => {
const d = new Date();
const when = new Date(d.setDate(d.getDate() + days));
return [new Date(), when].map(m=>getDateStr(m));
};
const limit = daysRange(-14);
const picker = document.getElementsByName("accident")[0];
picker.setAttribute('min', limit[1]);
picker.setAttribute('max', limit[0]);
picker.setAttribute('value', limit[0]);
label {
display: block;
font: 1rem 'Fira Sans', sans-serif;
}
input,
label {
margin: .4rem 0;
}
<label for="start">date:</label>
<input type="date" name="accident">
The solution you're looking for is something like this,
const twoWeeksAgo = 14 * 24 * 60 * 60 * 1000;
let dateElement = document.querySelector('#accident');
dateElement.min = new Date(Date.now() - twoWeeksAgo).toISOString().split('T')[0];
dateElement.max = new Date().toISOString().split('T')[0];
<input type="date" class="form-control" id="accident" name="accident" value="" title="Date of Accident">
You can use the max and min attributes of the HTML5 date element (documented here) to restrict your element to only show certain values.
In this particular case, the min attribute is set to the date (in yyyy-mm-dd format) two weeks ago and the max attribute is set to the current date.
The magic computation twoWeeksAgo is the number of milliseconds in 14 days which will allow you to compute the date 14 days ago.
The code new Date(Date.now() - twoWeeksAgo) gives us a Date object set to two weeks ago and the .toISOString() function returns the date in YYYY-MM-DDTHH:mm:ss.sssZ format, i.e., a date-time string.
Since the min attribute only requires the date and not the time, we then split the obtained string using 'T' as a delimiter, which would give us the date in YYYY-MM-DD format.
Putting it all together we get this line for the date two weeks ago
dateElement.min = new Date(Date.now() - twoWeeksAgo).toISOString().split('T')[0];
And similarly for the upper limit date,
dateElement.max = new Date().toISOString().split('T')[0];

Comparing input type date with current date

<input type="date" name="bday" id="biday" required>
I have to take the date from input type date field from the user and if the entered date is greater than the current date i have to print some error in the alert box. I Have tried various methods but none of them worked for input type date. I tried to take two variables one which stores the current date and the second which takes the value of date input element `
var startDate = Date(document.getElementByID('biday').value);
var today = new Date();
if (startDate > today) {
alert("The first date is after the second date!");
`.Can someone please help me the procedure to get the task done.
Here is the another way.
HTML
<input type="date" id="dval" value="" />
<button onclick="test()">TEsting</button>
JS
function test() {
var q = new Date();
var date = new Date(q.getFullYear(),q.getMonth(),q.getDate());
var mydate = new Date(document.getElementById('dval').value);
if(date > mydate) {
alert("Current Date is Greater THan the User Date");
} else {
alert("Current Date is Less than the User Date");
}
}
DEMO
Note: type="date" is not supported in Firefox, or Internet Explorer 11 and earlier versions.
You've got a little typo at getElementByID it should be getElementById
Also it is possible to compare date strings as the MYSQL Format 'YYYY-MM-DD' so you could actually compare two values directly as a string.
'2017-12-1' < '2017-12-3'
// true
If you are operating with another format you can either create a new Date Object and parse it to a TimeStamp like following:
// Receives a date String or Object
// and returns the aprox TimeStamp
function valueifyDate(date){
if(typeof date == 'object'){
return date.getTime();
}else{
return new Date(date).getTime();
}
}
var bday = document.getElementById('birthday');
bday.addEventListener("change", function(e){
var today = new Date();
if(valueifyDate(today) < valueifyDate(e.target.value)){
console.log("younger than today");
}
})
https://jsfiddle.net/jbnLx3v3/
To check whether you have date in startDate it is better to use Date.parse (which is implicitly used in Date constructor) and compare check if it is not NaN. As already mentioned, you need to get numeric value corresponding to the time by using today.getTime(). Then you can compare parsed startDate and today.getTime(). Also it should be getElementById not getElementByID. Please see corrected code below:
function compareDates() {
var startDate = Date.parse(document.getElementById('biday').value);
var today = new Date();
if (!isNaN(startDate) && startDate > today.getTime()) {
alert("The first date is after the second date!");
}
}
<input type="date" name="bday" id="biday" required onchange='compareDates()'>
There are number of errors on your code like getElementByID should be getElementById and you are not taking the value from input and so on. Check below snippet for reference.
function checkDate() {
var startDate = new Date(document.getElementById('biday').value);
var today = new Date();
if (startDate.getTime() > today.getTime()) {
alert("The first date is after the second date!");
}
}
<input type="date" name="bday" id="biday" required>
<input type="submit" value="check" onclick="checkDate()">

validate the form using javascript where i have from and to date picker and it should allow only current date and valid time not the next day

I have a form where have to enter from and to date in date picker , but while saving the data the from date and to date should be for the current date. And if i enter to date as tomorrows date it should not allow to save the date.Kindly let me know as how to do this in javascript. May I know what is the correct way to achieve my objective? And even say from time is 10 AM then to time should be 12 pm like not less than from time . Please advice in achieving this using javascript
var today = new Date();
var lastDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
$("#datepicker").datepicker({
startDate: today,
endDate: lastDate,
});
var counter=0;
$("#datepicker").change(function(){
var date1 = $("#datepicker").datepicker('getDate');
date1=date1.getDate();
if(today.getDate() != date1)
{
if(counter%2==0)
alert("please select current date");
}
counter++;
});
Check working fiddle http://jsfiddle.net/GX82L/15/
Done as per your expectation ,like it should prompt if other than current date is selected

Update Date with Javascript into Textbox add Months and correct year etc

So the premise is there is a text box that denotes the start date then another input box which onchange should run a javascript function that adds the value of months in the tenure box to the contract start date and give a contract end date.
I have tried the following code:
<form name="FormName">
Contract Start Date: <input type="text" name="Start" value="<?php echo date("Y/m/d"); ?>" onchange="myFunction()" />
<br />
Tenure (Months): <input type="text" name="Months" value="" onchange="myFunction()" />
<br />
Contract End Date: <input type="text" name="TextBoxName" value="" />
</form>
<script>
function myFunction()
{
var val = document.forms["FormName"].elements["Months"].value;
var d = new Date(document.forms["FormName"].elements["Start"].value);
var year = d.getFullYear();
var month = d.getMonth() + val;
var day = d.getDate();
document.forms["FormName"].elements["TextBoxName"].value = year + "/" + month + "/" + day;
}
</script>
But this does not seem to deal with it as a date object and I get values back like 2014/22/31 where 22 is the months and should obviously carry over to the year component.
I'm guessing its treating it as a string when the var's are defined into they're seperate Year, Month, Day parts... I need it to return a date that is in the format as date("Y/m/d"); in PHP.
Any assistance would be greatly appreciated!
as #user2310289 suggested, you should do this:
var endDate = new Date(d.setMonth(d.getMonth()+val));
var year = endDate.getFullYear();
var month = endDate.getMonth();
var day = endDate.getDate();
Try this:
// let your contract start date be '2013/12/11'
var c_start_date = '2013/12/10';
var tenure = 5; // 5 months
var c_start_date_obj = new Date(c_start_date);
var c_end_date_obj = new Date(c_start_date_obj.getFullYear(), c_start_date_obj.getMonth() + tenure, c_start_date_obj.getDate());
var c_end_date = c_end_date_obj.getFullYear() + '/' + c_end_date_obj.getMonth() + '/' + c_end_date_obj.getDate();
alert(c_end_date);
JSFiddle link
Your first issue is to correctly parse the date string. The format you are using is not one specified in ES5 so it will be entirely implementation dependent unless you parse it yourself. So:
// Parse y/m/d to create a Date
function parseString(s) {
s = s.split(/\D/);
return new Date(s[0], --s[1], s[2]);
}
Once you convert the string to a Date, you can add months:
var d = parseString(document.forms["FormName"].elements["Start"].value);
// Copy d for use later
oDate = d.getDate();
d.setMonth(d.getMonths() + Number(val));
You will have cases where you add months to a date that is say 31 July that will evaluate to say 31 June which will automatically be converted to 1 July.
You can fix this by looking at the date. If the adjusted date is not the same as the start date, set the adjusted date to the last day of the previous month by setting the date to 0, e.g.
if (d.getDate() != oDate) {
d.setDate(0);
}
Note that subtracting months may not get you back to the start, e.g.
Jan 31 + 1 month => 28 Feb // for a non-leap year
28 Feb - 1 month => 28 Jan
After a lot of playing around and searching the net I implemented the datejs library. This resolved a lot of the issues I was having.

Categories