HTML5 datepicker prevent past dates [duplicate] - javascript

This question already has answers here:
Disable certain dates from html5 datepicker
(6 answers)
Closed 9 years ago.
I am working on a website for booking movie tickets. What should I set the min attribute to, to prevent past dates in the HTML5 datepicker? (I do not want to use PHP solution mentioned here.)
Is there a pure HTML5/Javascript solution for this?

When the document loads have the date input disabled. Run an onload function that inserts today's date into the min field in the required format.
function onLoad() {
var input = document.getElementById("dateField");
var today = new Date();
// Set month and day to string to add leading 0
var day = new String(today.getDate());
var mon = new String(today.getMonth()+1); //January is 0!
var yr = today.getFullYear();
if(day.length < 2) { day = "0" + day; }
if(mon.length < 2) { mon = "0" + mon; }
var date = new String( yr + '-' + mon + '-' + day );
input.disabled = false;
input.setAttribute('min', date);
}
document.addEventListener('load', onLoad, false);
<body>
<input id="dateField" type="date" disabled />
</body>
Here it is in a fiddle: http://jsfiddle.net/tj9Xh/2/

try this:
<input id="dateField" type="date"/>
var dt= new Date();
var yyyy = dt.getFullYear().toString();
var mm = (dt.getMonth()+1).toString(); // getMonth() is zero-based
var dd = dt.getDate().toString();
var min = yyyy +'-'+ (mm[1]?mm:"0"+mm[0]) +'-'+ (dd[1]?dd:"0"+dd[0]); // padding
alert(min);
$('#dateField').prop('min',min);

Related

Unable to set min input hour and time to tomorrow 16h on <input type="datetime-local"> [duplicate]

I am using Modal for reminder date for task. The current date and the days before it has to be disabled so that the User can select the pick-up date starting next day inorder to Mark reminder with his specified task.
for this I am using input type :
<input type="datetime-local" class="form-control" autocomplete="off" id="actionreminderdate" />
If I use below java script it works for input type "Date" But not for Datetime-local.
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
/*alert(maxDate);*/
$('#actionreminderdate').attr('min', maxDate);
});
Can you help me with it?
You can set min and max values on the input field:
<input type="datetime-local" id="dateInput">
$(document).ready(function(){
elem = document.getElementById("dateInput")
var iso = new Date().toISOString();
var minDate = iso.substring(0,iso.length-1);
elem.value = minDate
elem.min = minDate
});
Get the current time in a recognised ISO format (you have to trim the zone data off the end, which is annoying), then set that as the input value and the input min.
https://jsfiddle.net/w8qgj543/24/

JavaScript - Trying to set tomorrow's date using the code below [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
var today = new Date();
var tomorrow = today.setDate(today.getDate() + 1)
console.log(tomorrow)
1596607917318
I am getting 13 digit number after using setDate(). How can I get the date in 2 digit format?
Date outputs in JS often need some manual processing to be exactly what you want. Try this:
// Create new Date instance
var today = new Date();
var tomorrow = today;
// Add a day
tomorrow.setDate(tomorrow.getDate() + 1)
console.log(formatDateToString(tomorrow));
function formatDateToString(date) {
var dd = (date.getDate() < 10 ? '0' : '')
+ date.getDate();
var MM = ((date.getMonth() + 1) < 10 ? '0' : '')
+ (date.getMonth() + 1);
return dd + "/" + MM;
}
The Date object has different methods that you can use to get certain parts of the timestamp.
// for day-month (i.e.: Oct 31 is 31-10
let formatted = `${tomorrow.getDate()}-${tomorrow.getMonth() + 1}`
See more: https://www.w3schools.com/js/js_date_formats.asp
setDate has changed the date of today.
Therefore output today and don't assign what's returned by setDate.
var today = new Date();
today.setDate(today.getDate() + 1);
console.log(today.toLocaleDateString());
Month is zero based so getMonth() + 1 returns this month, getDate() + 1 returns tomorrow.
var fecha = new Date();
var year = fecha.getFullYear();
var mes = fecha.getMonth() + 1;
var dia = fecha.getDate() + 1;
var hora = fecha.getHours();
var minutos = fecha.getMinutes();
var segundos = fecha.getSeconds();
var output = `Date: ${dia}/${mes}/${year}`+ '\n' + `Time: ${hora}:${minutos}:${segundos}`;
console.log(output)
Nice question, I recently had to do something similar in VB. Here is a simple javascript version, based on your code:
//this gets the date today
var today = new Date();
//we add one, to get the date tomorrow
var tomorrow = today.getDate() + 1
//if tomorrow is a single digit number, we just pad it with a zero
if (tomorrow < 10)
{
tomorrow = '0' + tomorrow
}
//write to the console
console.log(tomorrow)

How do I disable dates till current date? For input Type Datetime-local

I am using Modal for reminder date for task. The current date and the days before it has to be disabled so that the User can select the pick-up date starting next day inorder to Mark reminder with his specified task.
for this I am using input type :
<input type="datetime-local" class="form-control" autocomplete="off" id="actionreminderdate" />
If I use below java script it works for input type "Date" But not for Datetime-local.
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = year + '-' + month + '-' + day;
/*alert(maxDate);*/
$('#actionreminderdate').attr('min', maxDate);
});
Can you help me with it?
You can set min and max values on the input field:
<input type="datetime-local" id="dateInput">
$(document).ready(function(){
elem = document.getElementById("dateInput")
var iso = new Date().toISOString();
var minDate = iso.substring(0,iso.length-1);
elem.value = minDate
elem.min = minDate
});
Get the current time in a recognised ISO format (you have to trim the zone data off the end, which is annoying), then set that as the input value and the input min.
https://jsfiddle.net/w8qgj543/24/

Can not compare the given date with today date using Javascript

I am facing one issue. I need to compare the given date with the today date using Javascript. I am explaining my code below.
function getCurrentDate(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd;
}
if(mm<10)
{
mm='0'+mm;
}
today = dd+'-'+mm+'-'+yyyy;
return today;
}
var givendate=new Date('19-01-2018');
var todaydate=$scope.getCurrentDate();
if (givendate >= todaydate) {
console.log('bool',true);
}else{
console.log('bool',false);
}
Here I should get the result true but here I am getting the console message as false. Please help me to resolve this issue.
The below code works. Like the others said, you need to ensure that you are specifying the date in the proper format as expected by the Date constructor.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="today"></p>
<p id="text"></p>
<script>
today = new Date();
jan19 = new Date('2018-01-19')
document.getElementById("demo").innerHTML = jan19;
document.getElementById("today").innerHTML = today;
if (today < jan19) {
document.getElementById("text").innerHTML = 'true';
}
else {
document.getElementById("text").innerHTML = 'false';
}
</script>
</body>
</html>
As you said in the comments givendate is "Invalid Date" - that's why you have false.
So, before parsing a date, check how to detect invalid date
new Datetries to parse following ISO 8601 format. Quoting:
The formats are as follows. Exactly the components shown here must be present,
with exactly this punctuation. Note that the "T" appears
literally in the string, to indicate the beginning of the time
element, as specified in ISO 8601.
Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a
second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
Make sure you pass a correctly formatted date when constructing a date object. All the details you need on the subject can be found in JS MDN, on the Date.parse topic
If you want to continue with your current date format(dd-MM-yyyy), then you may need to split the string by - and rearrange accordingly to make a valid date.
JS Code
function getCurrentDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10)
dd = '0' + dd;
if (mm < 10)
mm = '0' + mm;
today = dd + '-' + mm + '-' + yyyy;
return today;
}
var todayDate = getCurrentDate().toString();
var givenDate = '19-01-2018';
var todayDateArray = todayDate.split('-');
var givenDateArray = givenDate.split('-');
todayDate = new Date(todayDateArray[2] + '-'
+ todayDateArray[1] + '-'
+ todayDateArray[0]);
givenDate = new Date(givenDateArray[2] + '-'
+ givenDateArray[1] + '-'
+ givenDateArray[0]);
if(givenDate >= todayDate)
console.log('bool', true);
else
console.log('bool', false);
This works for me. If you don't want a custom formatted date then you can use this.
function getCurrentDate(){
var today = new Date();
return today;
}
var givendate=new Date("2018-01-19");
var todaydate= getCurrentDate();
console.log(givendate);
console.log(todaydate);
if (givendate >= todaydate) {
console.log('bool',true);
}else{
console.log('bool',false);
}

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input [duplicate]

This question already has answers here:
How do I get the current date in JavaScript?
(61 answers)
Closed 8 years ago.
I would like to add a current date to a hidden HTML tag so that it can be sent to the server:
<input type="hidden" id="DATE" name="DATE" value="WOULD_LIKE_TO_ADD_DATE_HERE">
How can I add a formatted date to the VALUE attribute?
I hope this is what you want:
const today = new Date();
const yyyy = today.getFullYear();
let mm = today.getMonth() + 1; // Months start at 0!
let dd = today.getDate();
if (dd < 10) dd = '0' + dd;
if (mm < 10) mm = '0' + mm;
const formattedToday = dd + '/' + mm + '/' + yyyy;
document.getElementById('DATE').value = formattedToday;
How do I get the current date in JavaScript?
I honestly suggest that you use moment.js. Just download moment.min.js and then use this snippet to get your date in whatever format you want:
<script>
$(document).ready(function() {
// set an element
$("#date").val( moment().format('MMM D, YYYY') );
// set a variable
var today = moment().format('D MMM, YYYY');
});
</script>
Use following chart for date formats:
<input type="hidden" id="date"/>
<script>document.getElementById("date").value = new Date().toJSON().slice(0,10)</script>
To get current date/time in javascript:
var date = new Date();
If you need milliseconds for easy server-side interpretation use
var value = date.getTime();
For formatting dates into a user readable string see this
Then just write to hidden field:
document.getElementById("DATE").value = value;
By using the value attribute:
var today = new Date();
document.getElementById('DATE').value += today;
Use the DOM's getElementByid method:
document.getElementById("DATE").value = "your date";
A date can be made with the Date class:
d = new Date();
(Protip: install a javascript console such as in Chrome or Firefox' Firebug extension. It enables you to play with the DOM and Javascript)
You edit an element's value by editing it's .value property.
document.getElementById('DATE').value = 'New Value';

Categories