I've been searching everywhere but I can't seem to find what I'm looking for. I'm trying to find a basic Date and time picker as well as just a time picker that uses JavaScript.
My page is HTML5 and I know about the input types of datetime-local and time but they don't produce the correct format.
For datetime-local, the date and time is formated as:
yyyy-mm-ddThh:mm
I'm trying to find a way to just have the data saved in the field as mm-dd-yyyy hh:mm am/pm using JavaScript.
The page is simple so the user just fills in the above and then the date and time is stored in an element to be called using document.getElememtById
Same with the time only, looking for just a time JavaScript that uses the 12 hour format and the value is stored in an element called by getElementById.
I found things like libraries which I don't need for this simple page.
HTML5 introduced a bunch of new types you can use on a traditional input.
Browsers can use these types to show you context-specific keyboards (on touch screen devices), provide native input validation, and, in the case things like dates, surface a native date picker.
<input type="date">
Automatically setting today’s date
To automatically set a [type="date"] input to today’s date with vanilla JS, we’ll use the JavaScript Date() object.
First, we’ll get our field (let’s assume it has an ID of #today) and create a new Date() object.
var field = document.querySelector('#today');
var date = new Date();
The [type="date"] field looks different visually depending on where you live and what browser you’re using (it shows dates in local format norms), but the value follows a YYYY-MM-DD format.
We can get each of those values from our date, convert them to a string with toString(), and concatenate them into a single value.
We’ll use getFullYear() to get the year in a four-character format.
We’ll use getMonth() to get the month.
We’ll use getDate() to get the day.
For some absurd reason, the getMonth() method returns the month as a number starting with 0 (January is 0, February is 1, etc.). We need to add 1 to our result to get the correct month.
Because they’re numbers and not strings, both getMonth() and getDate() are missing leading zeros for single digit months/days. We can use the padStart() method to add those if missing.
Our finished result looks like this.
field.value = date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString().padStart(2, 0) +
'-' + date.getDate().toString().padStart(2, 0);
Let’s do a few things:
Add some helper text to our input label on the proper format that we can hide if the date input type is supported.
Add a pattern attribute to validate against for unsupported browsers.
Add a placeholder attribute with the pattern as well.
<label for="today">
The Date
<span class="description"> Please use the YYYY-MM-DD format</span>
</label>
<input
id="today"
type="date"
pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" placeholder="YYYY-MM-DD"
The JavaScript to set the date won’t change, but we can add some additional code to remove the pattern, placeholder, and helper text if not needed.
// Variables
var field = document.querySelector('#today');
var date = new Date();
// If [type="date"] is supported, update the DOM
if (isDateSupported()) {
// Remove attributes
field.removeAttribute('pattern');
field.removeAttribute('placeholder');
// Remove the helper text
var helperText = document.querySelector('[for="today"] .description');
if (helperText) {
helperText.parentNode.removeChild(helperText);
}
}
// Set the value
field.value = date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString().padStart(2, 0) +
'-' + date.getDate().toString().padStart(2, 0);
Here is a working example by Chris Fardinand
Related
I have input type="date" in my html page and I want to disable particular date through JavaScript. How can I do that?
I have tried to disable using getElementById but its disabling complete date input.
You can add a min or max attribute to the input type=date. The date must be in ISO format (yyyy-mm-dd). This is supported in many mobile browsers and current versions of Chrome, although users can manually enter an invalid date without using the datepicker.
<input name="somedate" type="date" min="2017-11-25">
The min and max attributes must be a full date; there's no way to specify "today" or "+0". To do that, you'll need to use JavaScript or a server-side language:
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("somedate")[0].setAttribute('min', today);
What we can’t do yet, however, is eliminate classes of days from our input. We can’t, for example, prevent selection of weekends or disallow Mondays purely through markup. Instead, we’ll need to do a little more work, using the HTML5 validation API, and the native JavaScript Date object.
code that will display an error if the date selected is a Monday.
var date = document.querySelector('[type=date]');
function noMondays(e){
var day = new Date( e.target.value ).getUTCDay();
// Days in JS range from 0-6 where 0 is Sunday and 6 is Saturday
if( day == 1 ){
e.target.setCustomValidity('OH NOES! We hate Mondays! Please pick any day but Monday.');
} else {
e.target.setCustomValidity('');
}
}
date.addEventListener('input',noMondays);
You could set a maximum/minimum on your date attribute like shown over here: https://www.w3schools.com/tags/att_input_min.asp
This however does not let you disable specific dates. If you really want this I would check if the selected date is allowed on posting the form.
You could get the selected date value on a submit like this in JQuery:
$('#submit').on('click', function(){
var date = new Date($('#date-input').val());
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
//Check here if date, month and year combination is allowed
});
In this example we have a date element with id 'date-input' and a button with id 'submit'.
Note that you should also check if the date is allowed on the server side.
I have a question that I am trying to solve for whole day.
I have Date and Time from Oracle DB that is shown on html page. I have jstl date formatter that has special pattern to show it. Let's take an example 09.05.2017 17:35 +0500 and pattern MM.dd.yyyy HH:mm Z. And I am getting it as String with jQuery . The first case: how to convert it to Date type without any changes. I tryed var date = new Date('09.05.2017 17:35 +0500') but if I have another time zone I'll recieve another UTC and time(hour) or maybe month etc.
Second: how to convert this time to UTC+0300.
I know one solution of this cases, but I think it's not easy. As I have constant pattern of Date, I can always parse the string and to write huge logic for solving second case. I am bad in JS and will be grateful for solution.
Regarding the parsing question, that is answered at Why does Date.parse give incorrect results? The bottom line is that you should parse the string manually and not rely on the built-in parser. A library can help, but if you only have one or two formats to deal with, writing your own parser isn't too difficult.
As for presenting time in a particular timezone, the same advice applies. If you always want UTC+0300, then start by knowing that javascript Dates are always UTC internally and have UTC methods to access those values. So you just change the UTC time by the required offset and format the date as required.
For formatting, see Where can I find documentation on formatting a date in JavaScript?
An example of adjusting the timezone:
// Return a string for UTC+0300 for the supplied date
// in dd-mm-yyyy hh:mm:ss format
function getUTC03(date) {
// Helper to pad with leading zero
function z(n){return ('0'+n).slice(-2)}
// Copy the date so don't affect original
var d = new Date(+date);
// Set UTC time to required offset
d.setUTCHours(d.getUTCHours() + 3);
// Format using UTC methods
return z(d.getUTCDate()) + '-' +
z(d.getUTCMonth()+1) + '-' +
d.getUTCFullYear() + ' ' +
z(d.getUTCHours()) + ':' +
z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) + ' ' +
'+0300';
}
console.log('Currently at +0300 it\'s ' + getUTC03(new Date()));
However, many places observe daylight saving. To adjust for that, a library is helpful. You just need to provide a location for which the offset can be determined for any particular date and time. Again, there are many questions here about that too.
Ok, so I am attempting to test if a date is older than today. I am using jQuery UI's Datepicker to parse the date and assign it to a variable:
//Get Date as String
var $strDate = $(".pmt-date").text();
//Parse Date
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
Then I get today's date and assign it to a variable:
//Get Today's Date
var $strToday $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
Now I would like to compare $dtDate with $tDate. This is what I have tried:
if($dtDate > $tDate)
{
alert("Payment Date is Greater");
}
else
{
alert("Today's Date is Greater");
}
When I test this, I ALWAYS get the alert "Today's Date is Greater". I can display my two date variables via an alert, and I see the dates in correct format. So why does this comparison fail to work when the parse is working correctly?
Assuming that the field with class "pmt-date" is the datepicker-controlled <input> element, you need to fetch its value with .val(), not .text().
var $strDate = $(".pmt-date").val();
Your next line of code refers to a variable called "$date", not "$strDate", so:
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
Once you've got that, you can just directly compare the Date objects:
if ($dtDate < new Date())
There's no need to turn a newly-constructed Date object into a string and then back into a date. I guess you're Date to string and back in order to strip off the time-of-day part of the date, so that's not really a bad way to do it.
In date comparisons, more than means the date comes after, and less than means the date comes before. Older than would imply that the date comes before, and thus you want to use less than
if($dtDate < $tDate)
I've created an app that takes in HTML inputs and goes through JavaScript to create an event on a native calendar events. It takes the time from the <input type="datetime-local">, and it's putting in a different time because it's picking a different time zone. If I enter 1 o'clock PM as a time it will return 8 o'clock AM.
<input type="datetime-local" id="startDate" name="startDate">
And the JavaScript:
var startDate = new Date($("#startDate").val());
Any help would be awesome. I can post more code if needed.
The HTML5 datetime-local input type will give you a string value back, which contains the date and time in ISO8601 format, with minute precision, and without any time zone offset.
For example: 2014-07-12T01:00
The JavaScript date object is notoriously inconsistent when it comes to parsing dates from strings. In most implementations, when you provide a string like this, it erroneously assumes the value is in UTC. Therefore, the Date object you get back will be adjusted by the time zone offset from your local computer.
There are two approaches to work around the problem:
Option 1
Manipulate the string to a format that will likely be interpreted as local time by the Date object's parser. Specifically, replace the dashes (-) with forward slashes (/) and replace the T with a space.
var s = $("#startDate").val();
var startDate = new Date(s.replace(/-/g,'/').replace('T',' '));
Option 2
Use a library with more capable date parsing abilities. There are several available. One of the most popular is moment.js.
Moment.js has lots of options, but it just so happens that the default behavior is exactly what you need. So you can just pass the string to the moment constructor without any parameters.
var s = $("#startDate").val();
var startDate = moment(s).toDate();
When writing a new date object with a string, one can write it as:
var someDay = new Date("12/01/2012");
This equals December 1st 2012.
However, what if the user has to fill in a date on a website where the format isn't month/day/year, but day/month/year? How would one go about creating a date object with the correct date then?
If you are getting the data as a string from another website, then you need to know the format in which that website provides you the date. There is no way around this because D-M-Y and M-D-Y are indistinguishable; even Y-M-D would be indistinguishable if they used a two-digit format for the year.
This hasn't been tested at all, but at worst the general idea should solve your problem.
var pattern = /^(\d+)\b(\d+)\b(\d+)$/;
if (!pattern.test(dateString))
return null;
var matches = dateString.match(pattern);
if (siteUsesDMY)
return new Date(matches[2], matches[1]-1, matches[0]);
if (siteUsesMDY)
return new Date(matches[2], matches[0]-1, matches[1]);
...
Pattern: This pattern supports any numeric representation of the date, assuming it has a breaking character between each unit. If you need to support a website that doesn't have a breaking character, you would need a different pattern that matched that website's exact format (i.e.: site sends DDMMYYYY, then pattern would be /^(\d{2})(\d{2})(\d{4})$/).
Also fixed the month parameter in date creation, as I just remembered that JavaScript uses 0-11 for months.