How to parse a time into a Date object from user input in JavaScript?
A quick solution which works on the input that you've specified:
function parseTime( t ) { var d = new Date(); var time = t.match( /(\d+)(?::(\d\d))?\s*(p?)/ ); d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) ); d.setMinutes( parseInt( time[2]) || 0 ); return d;}
var tests = [ '1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm', '1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400', '1000', '100', '123', '2459', '2359', '2359am', '1100', '123p', '1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) { console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );}
Parsing a string to a date in JavaScript
The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.
Examples of ISO format: YYYY-MM-DD
or YYYY-MM-DDTHH:MM:SS
.
But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.
To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z')
.
To display a date in UTC, use .toUTCString()
,
to display a date in user's local time, use .toString()
.
More info on MDN | Date and this answer.
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00')
. Note that the number of the month must be 1 less.
Alternate method - use an appropriate library:
You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.
How do I pass the value of an input type time to a Date object?
There's no need to use Date
and its methods the input is a String
so you better use .split(":")
method and you will get the hours
and minutes
values directly.
Then just test if their values are lower than 10
add a leading 0
and if the hours
is higher than 12
use pm
suffix or use am
otherwise.
This is a live DEMO using onchange event of the time input with its value as parameter onchange="ampm(this.value)
:
function ampm(time) {
console.log(time); if (time.value !== "") { var hours = time.split(":")[0]; var minutes = time.split(":")[1]; var suffix = hours >= 12 ? "pm" : "am"; hours = hours % 12 || 12; hours = hours < 10 ? "0" + hours : hours;
var displayTime = hours + ":" + minutes + " " + suffix; document.getElementById("display_time").innerHTML = displayTime; }}
<!--This is the input field where a user selects a time--><input id="time" placeholder="Time" type="time" name="time" onchange="ampm(this.value)" /><span id="display_time"></span>
Parse time string and convert it into a date object in Javascript
Let [ts, tz] = str.split(/[\+\-]/);
let [hr, min] = ts.split(':').map(Number);
let offsetSign = str.includes('+') ? 1 : -1;
let [offsetHr, offsetMin] = tz.split(':');
let offset = offsetSign * ((offsetHr * 1000 * 60 * 60) + (offsetMin * 1000 * 60));
let date = new Date();
date.setHour(hr);
date.setMinute(min);
let result = new Date(date.getTime() + offset);
Tedious, but not complex or difficult.
How do you parse a date from an HTML5 date input?
It's interpreting the date as UTC, which, for most time zones, will make it seem like "yesterday". One solution could be to add the time-zone offset back into the date to "convert" it to your local timezone.
Parse ONLY a time string with DateJS
Shortly after asking my question, I discovered that Date.parseExact() can take an array of format strings. Somehow I'm missed that. I managed to get something working with the following code:
function validateTime(input) {
return Date.parseExact(input, [
"H:m",
"h:mt",
"h:m t",
"ht","h t"]) != null ||
Date.parseExact(input, [
"h:mtt",
"h:m tt",
"htt","h tt"]) != null;
};
Note that some formats don't seem to be able to be included together at the same time, which is why I split them into two separate parseExact() calls. In this case, I couldn't include any string that contained a single t
in it with format strings that contained a double tt
in it.
Converting time string into Date object
To work with dates you can write your own parser or try already proven libraries like http://momentjs.com (what I would suggest to do).
How would I take a start/end dates user input, and convert it to US Pacific time, in ISO format?
Here is how you do it with dayjs
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");
dayjs.extend(utc);
dayjs.extend(timezone);
let t = dayjs()
.tz("America/Los_Angeles")
.utc(true)
.toISOString();
console.log(t);
Here is a list of all timezones https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
I personally live in europe, but when i execute this script it shows me the time in los angeles in ISO format
JavaScript date object from input type=date
how can I create the date object without parsing the string "Y-m-d" into pieces, or is the only way?
While Date.parse will convert strings in y/m/d/ format to date objects, manual parsing is the only sensible way:
// s is format y-m-d
// Returns a date object for 00:00:00 local time
// on the specified date
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
ES5 specifies a form of ISO 8601 that should be supported by all browsers, however it is not supported consistently or by all browsers in use.
Related Topics
Where to Write to Localstorage in a Redux App
Sort Mixed Alpha/Numeric Array
How to Copy Static Files to Build Directory with Webpack
Redirect a State to Default Substate with Ui-Router in Angularjs
How to Get Evaluated Attributes Inside a Custom Directive
How to Dynamically Insert a <Script> Tag via Jquery After Page Load
What Is the Motivation for Bringing Symbols to Es6
Does Never Resolved Promise Cause Memory Leak
How to Create a Dialog with "Ok" and "Cancel" Options
Dynamic Function Name in JavaScript
What's the Difference Between Window.Location= and Window.Location.Replace()
Getting Unexpected Token Export
How to Parse a Time into a Date Object from User Input in JavaScript
How Can Jquery Deferred Be Used
Using Address Instead of Longitude and Latitude with Google Maps API
How to Get the Fragment Identifier (Value After Hash #) from a Url