Date and time parsing in JavaScript - javascript

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.

Related

How to convert date like '2021-06-01T11:17:00-07:00' to get date time for particular location (New Delhi) in javascript?

How to convert date like '2021-06-01T11:17:00-07:00' to ISO standard? What is this format?
let date = new Date('2021-06-01T11:17:00-07:00');
console.log(date.getHours() + " :" + date.getMinutes());
I should get 11:17 but I am getting back 23:47
So something going wrong in understanding the correct format of date?
To reverse engineer,
If I convert date my expected date which is "2021-06-01 11:17:00" to IsoString then the value which I get is 2021-06-01T05:47:00.000Z
which is not equal to 2021-06-01T11:17:00-07:00
PS - So from comments I got to know this format is in MST which is 7 hours behind UTC
The input specifies a time zone, so it specifies a time at which in Salt Lake City it is 11:17. That same moment corresponds to 23:47 in New Delhi, which is your time zone.
So when you tell JavaScript to read the input, it will know it is a specification in Mountain Standard Time (-07:00), and will store the date in UTC. When you output the date as you do, JavaScript will use your locale and output it as 23:47, which is the exact same moment that the input specifies.
If you want the time to output as 11:17, then apparently you don't want to consider that it is a local time in Salt Lake City, but ignore that, and just consider it to be 11:17 in your time zone.
In that case, you should change the input, and remove the time zone specification:
let date = new Date('2021-06-01T11:17:00'); // No time zone specified -> is interpreted as local time
console.log(date.getHours() + " :" + date.getMinutes());
If the input string is variable, you can strip the time zone by keeping only the first 19 characters of the input before passing it to the Date constructor.
But be aware that when you strip the time zone, you actually change the time specification in the input to a different one. It is no longer the same time.
Have you tried using the Vanilla javascript Date class? Should be able to pass that into the constructor and then convert it to the desired format. For example:
const date2 = new Date('1995-12-17T03:24:00');
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
You could also try using the Moment library in Javascript, although many people are trying to move away from this.

Format JSON DateTime

I currently have all my dates being returned with the letter T in my JSON Strings. EX: 2019-02-03T06:48:07. Is there a way to change the JSON String to return as 02-03-2019 06:48:07?
I am also using javascript to load the dates currently into a data table.
You can convert your string into a Date object and then format it like this:
let jsonString = "2019-02-03T06:48:07";
// You should set your own timezone and options.
console.log(new Date(jsonString).toLocaleString('en-US', {hour12: false}))
For more information, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
The T is there because this is a standard ISO 8601 format. It makes it very easy to parse on the client side:
var myDate = new Date('2019-02-03T06:48:07')
With myDate you can then do whatever formatting you wish. Assuming you have another function to handle leading zeros, that could be something like:
var myFormattedDate = padLeft(myDate.getMonth() + 1, '0') + '-' +
padLeft(myDate.getDay(), '0') + '-'
myDate.getFullYear() + ' ' +
// etc
Note that your timestamp lacks any timezone information. With this code it will be interpreted on the client side in whatever the local timezone of the user is. If it is UTC time, then you can correct for this by adding either 'Z' or '+00:00' onto the timestamp before parsing in the Date constructor.
If you are able to add a library to assist, this all becomes much easier with moment.js:
myFormattedDate = moment('2019-02-03T06:48:07').format('MM/DD/YYYY HH:mm:ss');

JavaScript Date and Time Picker

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

Reversing epoch time conversion

Im using moment.js to convert a long/epoch time in to a humane readable format:
function convertValue(x) {
var mytime = x; // x = 1460554200000000
mytime = moment.utc(mytime).utcOffset(moment().format('ZZ'));
mytime = mytime.format('DD-MM-YY HH:mm:ss.SSS');
mytime = mytime + ' (' + moment().format('[UTC]ZZ') + ')';
return myTime;
}
Which myTime would return something like: 14-05-16 15:55:05.000 (UTC+100)
How can i do the opposite, so, if i was to receive something like: 29-01-16 14:35:05.000 (UTC+100) and convert back to an epoch time?
For a given moment object, if you want the result as a string:
Use .format('x') for the timestamp in milliseconds
Use .format('X') for the timestamp in seconds
However, if you want the result as a number:
Use .valueOf() for the timestamp in milliseconds
Use .unix() for the timestamp in seconds
However, with regards to the code you provided:
The offset UTC+100 is nonstandard and somewhat ambiguous. It could be UTC+10, UTC+10:00, UTC+0100, or UTC+01:00.
DD-MM-YY may be confusing to users, as it using two digit years, and is in reverse order of what is usually expected. Use YYYY-MM-DD if you're intending it to be used by a large number of people, or if you're going for something locale specific then make sure you're using separators that are common in the locale. Usually / or .
You're pairing the timestamp given with the current offset, rather than the offset in effect at the given time. That's going to fail in many locations where the time zone offset changes for daylight saving time and other time zone changes.
Your code should just be:
var mytime = moment(x).format('YYYY-MM-DD HH:mm:ss.SSS [UTC]ZZ');
To create a moment object from a string in a particular format, simply provide that format when parsing. So, the reverse function would be:
var x = moment(mytime, 'YYYY-MM-DD HH:mm:ss.SSS [UTC]ZZ').valueOf();
As long as you can coerce it back in to a moment object, you should be able to use moment().format('x') to get back to a Unix timestamp.
If you're talking about parsing a non standard date string in to a moment object, that's a lot more difficult. Since you know the format it was output as you should be able to use moment(dateString, formatString) to create a moment out of it.

strptime in Javascript

I have a date input field that allows the user to enter in a date and I need to validate this input (I already have server side validation), but the trick is that the format is locale dependent. I already have a system for translating the strptime format string to the the user's preference and I would like to use this same format for validating on the Javascript side.
Any ideas or links to a strptime() implementation in Javascript?
After a few days of googling I found this implementation which, although not complete, seems to handle all of the cases I have right now.
I've just added our php.js implementation of strptime(); I've tested it a bit, but it needs further unit testing. Anyhow, feel free to give it a shot; it should cover everything that PHP does (except for not yet supporting the undocumented %E... (alternative locale format) specifiers).
Note that it also depends on our implementation of setlocale() and array_map()...
https://github.com/kvz/phpjs/blob/master/functions/strings/setlocale.js
https://github.com/kvz/phpjs/blob/master/functions/array/array_map.js
Here is an example function that duplicates most of the functionality of strptime. The JavaScript date object generally will parse any date string you throw at it so you don't have to worry to much about that. So once you have a date object based off of your string you just push each element into a JS object and return it. This site has a good reference to the properties of the JavaScript date object: http://www.javascriptkit.com/jsref/date.shtml
function strptime(dateString){
var myDate = new Date(dateString);
return {tm_sec:myDate.getSeconds(),
tm_min: myDate.getMinutes(),
tm_hour: myDate.getHours(),
tm_mday: myDate.getDate(),
tm_mon: myDate.getMonth(),
tm_year: myDate.getFullYear().toString().substring(2),
tm_wday: myDate.getDay()};
}
var dateString = "October 12, 1988 13:14:00";
dateObj = strptime(dateString);
document.write("d:" + dateObj.tm_min + "/" + dateObj.tm_hour + "/" + dateObj.tm_mday + "/" + dateObj.tm_mon + "/" + dateObj.tm_year);

Categories

Resources