Created
October 29, 2019 01:38
-
-
Save joe-oli/951d9c25ae0b030cf00d10f003c433f3 to your computer and use it in GitHub Desktop.
parse XML dates in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let myXmlDate = "2019-12-31T14:30:50"; | |
let myJsDate = new Date(myXmlDate); //THIS WILL WORK IN MODERN BROWSERS. | |
For other such as ancient IE7,8 (but i dont give a flock for those anymore), you can manually parse the string and | |
manually create a date object. It's not hard: | |
( Answer from here: https://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object ) | |
var dateString = '2011-11-12T13:00:00-07:00'; | |
function dateFromString(s) { | |
var bits = s.split(/[-T:]/g); | |
var d = new Date(bits[0], bits[1]-1, bits[2]); | |
d.setHours(bits[3], bits[4], bits[5]); | |
return d; | |
} | |
You probably want to set the time for the location, so you need to apply the timezone offset to the created time object, it's not hard except that javascript date objects add the offset in minutes to the time to get UTC, whereas most timestamps subtract the offset (i.e. -7:00 means UTC - 7hrs to get local time, but the javascript date timezone offset will be +420). | |
Allow for offset: | |
function dateFromString(s) { | |
var bits = s.split(/[-T:+]/g); | |
var d = new Date(bits[0], bits[1]-1, bits[2]); | |
d.setHours(bits[3], bits[4], bits[5]); | |
// Get supplied time zone offset in minutes | |
var offsetMinutes = bits[6] * 60 + Number(bits[7]); | |
var sign = /\d\d-\d\d:\d\d$/.test(s)? '-' : '+'; | |
// Apply the sign | |
offsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes); | |
// Apply offset and local timezone | |
d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset()) | |
// d is now a local time equivalent to the supplied time | |
return d; | |
} | |
Of course is it much simpler if you use UTC dates and times, then you just create a local date object, setUTCHours, then date and you're good to go - the date object will do the timezone thing (provided the local system has it set correctly of course...). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment