How can I convert datetime microformat to local time in javascript? - javascript

I have a page that is currently using the datetime microformat to display a timestamp, but I have only been showing the human-readable time for my own time zone:
<abbr class="published" title="2009-01-09T09:16:00-05:00">
Friday, January 9, 2009 at 9:16 am (EST)</abbr>
What I'd like to do is rewrite the innerHTML for the abbr tag to be the same format, but in the user's local timezone. So for a reader in Seattle, the above should be converted to:
<abbr class="published" title="2009-01-09T09:16:00-05:00">
Friday, January 9, 2009 at 6:16 am (PST)</abbr>
I've looked at the Javascript Date object, which allows me to get the local timezone offset. But I have a few problems:
I don't see an easy way to create a new Date object from an ISO-8601 timestamp. (I suppose I could parse with substrings or regex if there's no faster way.)
I don't see a way to get the named abbreviation for the timezone. For example, for a reader in Seattle, I'd want the time to have "(PST)" appended to the end, otherwise it is not clear to that user that the timestamp has been converted (especially if he is a frequent visitor and has become accustomed to the fact that my times are in EST).

Here is code of mine that parses an ISO timestamp:
function isoDateStringToDate (datestr) {
if (! this.re) {
// The date in YYYY-MM-DD or YYYYMMDD format
var datere = "(\\d{4})-?(\\d{2})-?(\\d{2})";
// The time in HH:MM:SS[.uuuu] or HHMMSS[.uuuu] format
var timere = "(\\d{2}):?(\\d{2}):?(\\d{2}(?:\\.\\d+)?)";
// The timezone as Z or in +HH[:MM] or -HH[:MM] format
var tzre = "(Z|(?:\\+|-)\\d{2}(?:\\:\\d{2})?)?";
this.re = new RegExp("^" + datere + "[ T]" + timere + tzre + "$");
}
var matches = this.re.exec(datestr);
if (! matches)
return null;
var year = matches[1];
var month = matches[2] - 1;
var day = matches[3];
var hour = matches[4];
var minute = matches[5];
var second = Math.floor(matches[6]);
var ms = matches[6] - second;
var tz = matches[7];
var ms = 0;
var offset = 0;
if (tz && tz != "Z") {
var tzmatches = tz.match(/^(\+|-)(\d{2})(\:(\d{2}))$/);
if (tzmatches) {
offset = Number(tzmatches[2]) * 60 + Number(tzmatches[4]);
if (tzmatches[1] == "-")
offset = -offset;
}
}
offset *= 60 * 1000;
var dateval = Date.UTC(year, month, day, hour, minute, second, ms) - offset;
return new Date(dateval);
}
Unfortunately, it doesn't handle timezone abbreviations either. You would have to modify the "tzre" expression to accept letters, and the only solution I know of to deal with timezone abbreviations in Javascript is to have a look-up table which you keep up to date manually in the event of changes to regional daylight savings times.

EcmaScript formalized the addition of an ISO-8601 style string as an imput for a JavaScript date. Since most JS implementations don't support this, I created a wrapper to the Date object, that has this functionality. If you set the title tags to output in UTC/GMT/Z/Zulu offset, you can use my EcmaScript 5 extensions for JS's Date object.
For DateTime values that are to be used in client-side scripts, I generally try to always do the following. Store date+time in UTC zone (even in databases). Transmit date-times in UTC zone. From client to server, you can use the .toISOString() method in the above link. From server-to client this is relatively easy.
Via jQuery (with extension):
$('.published').each(function(){
var dtm = new Date(this.title);
if (!isNaN(dtm)) {
this.text(dtm.toString());
}
});
I don't recall if I added support for non-utc date-times in the input, but wouldn't be too hard to account for them.

Related

How to reposition datetime into the current timezone when converting an ISO 8601 datetime string to a **Date** object?

Let's say we're in London at midnight on 2020-01-01 and make an entry into an app that stores the datetime as an ISO-8601 string like this.
2020-01-01T00:00:00-00:00
Later, I am in Los Angeles and want to view this date on a chart that requires a javascript date object.
Getting the localized date object is easy.
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theDate = new Date(iso8601Date);
console.log(typeOf(theDate)); // date
console.log(theDate); // Tue Dec 31 2019 16:00:00 GMT-0800 (PST)
But, sometimes we want to "ignore" the timezone offset and analyze the data as if it happened in the current timezone.
This is the result I'm looking for but don't know how to accomplish.
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theRepositionedDate = someMagic(iso8601Date);
console.log(typeOf(theRepositionedDate)); // date
console.log(theRepositionedDate); // Wed Jan 01 2020 00:00:00 GMT-0800 (PST)
How do you reposition the date and return a date object?
/* Helper function
Returns the object type
https://stackoverflow.com/a/28475133/25197
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
*/
function typeOf(obj) {
return {}.toString
.call(obj)
.split(' ')[1]
.slice(0, -1)
.toLowerCase();
}
This is really a duplicate of Why does Date.parse give incorrect results?, but that may not seem apparent at first glance.
The first rule of parsing timestamps is "do not use the built–in parser", even for the 2 or 3 formats supported by ECMA-262.
To reliably parse a timestamp, you must know the format. Built–in parsers try and work it out, so there are differences between them that may well produce unexpected results. It just happens that '2020-01-01T00:00:00+00:00' is probably the only supported format that is actually reliably parsed. But it does differ slightly from strict ISO 8601, and different browsers differ in how strictly they apply the ECMAScript parsing rules so again, very easy to get wrong.
You can convert it to a "local" timestamp by just trimming the offset information, i.e. '2020-01-01T00:00:00', however Safari at least gets it wrong and treats it as UTC anyway. ECMAScrip itself is inconsistent with ISO 8601 by treating date–only forms of ISO 8601 as UTC (i.e. '2020-01-01' as UTC when ISO 8601 says to treat it as local).
So just write your own parser or use a library, there are plenty to choose from. If you're only looking for parsing and formatting, there are some that are less than 2k minified (and there are examples on SO).
Writing your own is not that challenging if you just want to support straight forward ISO 8601 like formats, e.g.
// Parse ISO 8601 timestamps in YYYY-MM-DDTHH:mm:ss±HH:mm format
// Optional "T" date time separator and
// Optional ":" offset hour minute separator
function parseIso(s, local) {
let offset = (s.match(/[+-]\d\d:?\d\d$/) || [])[0];
let b = s.split(/\D/g);
// By default create a "local" date
let d = new Date(
b[0],
b[1]-1,
b[2] || 1,
b[3] || 0,
b[4] || 0,
b[5] || 0
);
// Use offset if present and not told to ignore it
if (offset && !local){
let sign = /^\+/.test(offset)? 1 : -1;
let [h, m] = offset.match(/\d\d/g);
d.setMinutes(d.getMinutes() - sign * (h*60 + m*1) - d.getTimezoneOffset());
}
return d;
}
// Samples
['2020-01-01T00:00:00+00:00', // UTC, ISO 8601 standard
'2020-01-01 00:00:00+05:30', // IST, missing T
'2020-01-01T00:00:00-0400', // US EST, missing T and :
'2020-01-01 00:00:00', // No timezone, local always
'2020-01-01' // Date-only as local (differs from ECMA-262)
].forEach(s => {
console.log(s);
console.log('Using offset\n' + parseIso(s).toString());
console.log('Ignoring offset\n' + parseIso(s, true).toString());
});
Building off of #RobG's answer I was able to speed this one up a little by using a single regex. Posting here for posterity.
const isoToDate = (iso8601, ignoreTimezone = false) => {
// Differences from default `new Date()` are...
// - Returns a local datetime for all without-timezone inputs, including date-only strings.
// - ignoreTimezone processes datetimes-with-timezones as if they are without-timezones.
// - Accurate across all mobile browsers. https://stackoverflow.com/a/61242262/25197
const dateTimeParts = iso8601.match(
/(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:([+-])(\d{2}):(\d{2}))?)?/,
);
// Create a "localized" Date by always specifying a time. If you create a date without specifying
// time a date set at midnight in UTC Zulu is returned. https://www.diigo.com/0hc3eb
const date = new Date(
dateTimeParts[1], // year
dateTimeParts[2] - 1, // month (0-indexed)
dateTimeParts[3] || 1, // day
dateTimeParts[4] || 0, // hours
dateTimeParts[5] || 0, // minutes
dateTimeParts[6] || 0, // seconds
dateTimeParts[7] || 0, // milliseconds
);
const sign = dateTimeParts[8];
if (sign && ignoreTimezone === false) {
const direction = sign === '+' ? 1 : -1;
const hoursOffset = dateTimeParts[9] || 0;
const minutesOffset = dateTimeParts[10] || 0;
const offset = direction * (hoursOffset * 60 + minutesOffset * 1);
date.setMinutes(date.getMinutes() - offset - date.getTimezoneOffset());
}
return date;
};
The key difference is a single regex that returns all the matching groups at once.
Here's a regex101 with some examples of it matching/grouping.
It's about double the speed of the #RobG's awesome accepted answer and 4-6x faster than moment.js and date-fns packages. 👍
const createDate = (isoDate) => {
isoDate = new Date(isoDate)
return new Date(Date.UTC(
isoDate.getUTCFullYear(),
isoDate.getUTCMonth(),
isoDate.getUTCDate(),
isoDate.getUTCMinutes(),
isoDate.getUTCSeconds(),
isoDate.getUTCMilliseconds()
));
}
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theRepositionedDate = createDate(iso8601Date);
console.log(theRepositionedDate instanceof Date); // true
console.log(theRepositionedDate);
But, sometimes we want to "ignore" the timezone offset and analyze the data as if it happened in the current timezone.
Ok, then ignore it.
const iso8601Date = '2020-01-01T00:00:00+00:00';
const theDate = new Date(iso8601Date.substring(0, 19));
This works because you're creating a Date object from 2020-01-01T00:00:00 - an ISO 8601 date-time without offset.
ECMAScript section 20.3.1.15 - Date Time String Format says:
When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

What is the difference in these timestamps?

So I am trying to make a post request to an API, and one of the values required is a date that according to there documentation should be in the following format
Start time of the timesheet, in ISO 8601 format
(YYYY-MM-DDThh:mm:ss±hh:mm). Time should reflect the user's local time.
But when I try to make a new Date().toISOString() value in the ISO format I get this
2019-07-17T19:50:08.057Z
So I guess my question is, how can I produce the supposed format that they are looking for which is apparently a different ISO 8601 format? Or what would be the format for the following timestamp?
2018-07-25T13:10:23-07:00
here is the documentation to the api that I am playing around with https://tsheetsteam.github.io/api_docs/#create-timesheets
Your question is similar to Javascript date format like ISO but local but you want the timezone also, so:
function toISOLocal(date) {
// Pad single digit numbers with leading zero
function z(n){return (n<10?'0':'')+n}
// Copy the input date
var d = new Date(date);
// Get offset and adjust
var offset = d.getTimezoneOffset();
d.setMinutes(d.getMinutes() - offset);
// Build timestamp with adjusted date and local offset
var sign = offset < 0? '+' : '-';
offset = Math.abs(offset);
var offsetStr = sign + z(offset/60|0) + ':' + z(offset%60);
return d.toISOString().replace(/z$/i, offsetStr);
}
console.log(toISOLocal(new Date()));
However I suspect you can get by with the built–in toISOString and just replace the trailing Z with +00:00. You might need to remove the decimal seconds part also:
function modifyISO(d) {
return d.toISOString().replace(/\.\d+/, '').replace(/z$/i,'+00:00');
}
console.log(modifyISO(new Date()));
Just remove the tail. Something like this.
console.log(new Date().toISOString().replace(/(.+)(\..+?$)/g,'$1'));
You need set location time to make reference to meridian 0 + or - , you can set with library like momentjs, basically you set a reference to compare
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00

Javascript Date parsing returning strange results in Chrome

I observed some strange Date behaviour in Chrome (Version 74.0.3729.131 (Official Build) (64-bit)).
Following javascript was executed in the Chrome Dev Console:
new Date('1894-01-01T00:00:00+01:00')
// result: Mon Jan 01 1894 00:00:00 GMT+0100 (Central European Standard Time)
new Date('1893-01-01T00:00:00+01:00')
// result: Sat Dec 31 1892 23:53:28 GMT+0053 (Central European Standard Time)
I have already read about non standard date parsing via the Date ctor in different browsers, although providing valid ISO8601 values.
But this is more than strange o_o
In Firefox (Quantum 66.0.3 (64-Bit)) the same calls result in expected Date objects:
new Date('1894-01-01T00:00:00+01:00')
// result: > Date 1892-12-31T23:00:00.000Z
new Date('1893-01-01T00:00:00+01:00')
// result: > Date 1893-12-31T23:00:00.000Z
Is this a bug in Chrome?
My input is valid ISO8601 i guess?
The most important question is, how do I fix this? (hopefully without parsing the input string myself)
Okay, seems like this behaviour cannot be avoided, so you should parse dates manually. But the way to parse it is pretty simple.
If we are parsing date in ISO 8601 format, the mask of date string looks like this:
<yyyy>-<mm>-<dd>T<hh>:<mm>:<ss>(.<ms>)?(Z|(+|-)<hh>:<mm>)?
1. Getting date and time separately
The T in string separates date from time. So, we can just split ISO string by T
var isoString = `2019-05-09T13:26:10.979Z`
var [dateString, timeString] = isoString.split("T")
2. Extracting date parameters from date string
So, we have dateString == "2019-05-09". This is pretty simple now to get this parameters separately
var [year, month, date] = dateString.split("-").map(Number)
3. Handling time string
With time string we should make more complex actions due to its variability.
We have timeString == "13:26:10Z"
Also it's possible timeString == "13:26:10" and timeString == "13:26:10+01:00
var clearTimeString = timeString.split(/[Z+-]/)[0]
var [hours, minutes, seconds] = clearTimeString.split(":").map(Number)
var offset = 0 // we will store offset in minutes, but in negation of native JS Date getTimezoneOffset
if (timeString.includes("Z")) {
// then clearTimeString references the UTC time
offset = new Date().getTimezoneOffset() * -1
} else {
var clearOffset = timeString.split(/[+-]/)[1]
if (clearOffset) {
// then we have offset tail
var negation = timeString.includes("+") ? 1 : -1 // detecting is offset positive or negative
var [offsetHours, offsetMinutes] = clearOffset.split(":").map(Number)
offset = (offsetMinutes + offsetHours * 60) * negation
} // otherwise we do nothing because there is no offset marker
}
At this point we have our data representation in numeric format:
year, month, date, hours, minutes, seconds and offset in minutes.
4. Using ...native JS Date constructor
Yes, we cannot avoid it, because it is too cool. JS Date automatically match date for all negative and too big values. So we can just pass all parameters in raw format, and the JS Date constructor will create the right date for us automatically!
new Date(year, month - 1, date, hours, minutes + offset, seconds)
Voila! Here is fully working example.
function convertHistoricalDate(isoString) {
var [dateString, timeString] = isoString.split("T")
var [year, month, date] = dateString.split("-").map(Number)
var clearTimeString = timeString.split(/[Z+-]/)[0]
var [hours, minutes, seconds] = clearTimeString.split(":").map(Number)
var offset = 0 // we will store offset in minutes, but in negation of native JS Date getTimezoneOffset
if (timeString.includes("Z")) {
// then clearTimeString references the UTC time
offset = new Date().getTimezoneOffset() * -1
} else {
var clearOffset = timeString.split(/[+-]/)[1]
if (clearOffset) {
// then we have offset tail
var negation = timeString.includes("+") ? 1 : -1 // detecting is offset positive or negative
var [offsetHours, offsetMinutes] = clearOffset.split(":").map(Number)
offset = (offsetMinutes + offsetHours * 60) * negation
} // otherwise we do nothing because there is no offset marker
}
return new Date(year, month - 1, date, hours, minutes + offset, seconds)
}
var testDate1 = convertHistoricalDate("1894-01-01T00:00:00+01:00")
var testDate2 = convertHistoricalDate("1893-01-01T00:00:00+01:00")
var testDate3 = convertHistoricalDate("1894-01-01T00:00:00-01:00")
var testDate4 = convertHistoricalDate("1893-01-01T00:00:00-01:00")
console.log(testDate1.toLocaleDateString(), testDate1.toLocaleTimeString())
console.log(testDate2.toLocaleDateString(), testDate2.toLocaleTimeString())
console.log(testDate3.toLocaleDateString(), testDate3.toLocaleTimeString())
console.log(testDate4.toLocaleDateString(), testDate4.toLocaleTimeString())
Note
In this case we are getting Date instance with all its own values (like .getHours()) being normalized, including timezone offset. The testDate1.toISOString will still return weird result. But if you are working with this date, it will probably 100% fit your needings.
Hope that helped :)
This might be the case when all browsers follow their own standards for encoding date formats (but I am not sure on this part). Anyways a simple fix for this is to apply the toISOString method.
const today = new Date();
console.log(today.toISOString());

Comparing 2 strings with number values JS

Im trying to check to see if current time is lower than time that is responded from an API. Problem is they are both strings. The API response contains characters such as : and -, so parseInt is not working (at least that's my theory why its not working)
var d = new Date();
var hour = d.getHours();
var minutes = d.getMinutes();
var year = d.getFullYear();
var month = d.getMonth() +1;
var day = d.getDate();
var seconds = d.getSeconds();
var time = year+'-'+month+'-'+day+' '+hour+':'+minutes+':'+seconds;
time returns
"2016-11-7 15:48:2"
API Response is
"2016-11-07 20:06:00"
I have confirmed they are both strings
time < APIresponse
Always returns false
Are there any known solutions? Thanks in advance.
Preface: Timezone
Your current code assumes that the date/time you're getting from the API is in "local time," because you're comparing it with the current date/time in the browser's local timezone. APIs frequently provide date/times in UTC rather than "local" time, so beware of that assumption and double-check it.
If you want to do it at the string level
...you need to ensure when building time that you zero-pad the numbers, so for instance not just 7 for the day of the month, but 07. Then you'll end up with strings that have the fields in a valid comparable order (because the most significant field [year] is first, and the least significant field [seconds] is last), so a lexicographic comparison of the strings is valid.
So for instance, you'd create time like this:
var time = pad(year, 4) + '-' + pad(month, 2) + '-' + pad(day, 2) + ' ' + pad(hour, 2) + ':' + pad(minutes, 2) + ':' + pad(seconds, 2);
...where pad is a function you define that adds as many 0s as needed to ensure the string is as long as the second argument defines.
Then you can do:
if (time < timeStringFromAPI)
Note: If the API's response is giving you the date/time in UTC rather than local time, you'll need to use the UTC version of the accessor functions (e.g., getUTCHours, getUTCFullYear, etc.) rather than the ones you're using, which are for local time.
If you want to do it at the date level
...then you need to convert the date you're getting from the API to a Date. It's almost in a form you can reliable parse on modern browsers,
but not quite; some browsers will parse that string as local time, others as UTC.
If you're sure it's in local time, then the best thing to do is split it into its parts and use the multipart Date constructor:
var parts = timeStringFromAPI.split(/[-:]/);
var apiDate = new Date(
+parts[0], // Year
+parts[1] - 1, // Month
+parts[2], // Day
+parts[3], // Hours
+parts[4], // Minutes
+parts[5] // Seconds
);
If you're sure it's in UTC, then you can either do the above but with new Date(Date.UTC(...)) rather than just new Date(...), or you can put the string into the JavaScript date/time format and parse that:
var apiDate = new Date(timeStringFromAPI.replace(" ", "T") + "Z");
That takes the "2016-11-07 20:06:00" and changes it to "2016-11-07T20:06:00Z", which can reliably be parsed on all non-obsolete browsers.
Then you can do
if (new Date() < apiDate) {
try this :
var curDate = new Date();
then compare in this way
if (new Date(yourdate) <= curDate)
{
something...
}
var d1 = "2016-11-7 15:48:2";
var d2 = "2016-11-07 20:06:00";
if (new Date(d1) < new Date(d2)) {
alert('true')
}

creating date from a timestring in javascript

I am new to javascript and am trying to compare two date values ,I am getting two time value strings in the format
06:30:47 AM
01:10:47 PM
I need to compare these to find out if the first one is less than the other.I couldn't figure out how to do this in javascript.Can someone help?
o.h
I do not think that the standard implementation can parse this. I would do something like this:
function toDate(dateString) {
var timeComponents = dateString.replace(/\s.*$/, '').split(':');
if (dateString.indexOf("PM") > -1) {
timeComponents[0] += 12;
}
var date = new Date();
date.setHours(timeComponents[0]);
date.setMinutes(timeComponents[1]);
date.setSeconds(timeComponents[2]);
return date;
}
if (toDate('06:30:47 AM') > toDate('01:10:47 PM')) {
// ...
}
JavaScript's specified date/time parsing, what you can rely upon cross-browser, is surprisingly limited. For a long time, there was no single string date format that was mandated in the spec, and as of the recent 5th edition spec, the only mandated format is ISO-8601 (and some subsets). You can't yet rely on browsers having implemented that part of the 5th edition spec.
So you have a couple of choices:
Parse the string yourself and use the Date constructor that takes the individual parts of the date as numbers, e.g. new Date(year, month, day, hour, minute, second, ...). (You need only specify as many of those as you want, so for instance new Date(2010, 9, 14) is September 14th, 2010.)
Use a library like Moment that's already done the work for you. Moment lets you specify the format to parse.
Use the Date object. Check this: http://www.w3schools.com/jsref/jsref_obj_date.asp
Try putting the two values in Date variables and do this:
if(var1.valueOf() > var2.valueOf())
{
//Do Something
}
If your times are always in the format 00:00:00 AM then
var a="06:30:47 AM";
var b="01:10:47 PM";
var at=parseInt(a.substring(0,8).replace(/(^0+|:)/g,""));
var bt=parseInt(b.substring(0,8).replace(/(^0+|:)/g,""));
if (a.charAt(9)=="P") {at=at+120000};
if (b.charAt(9)=="P") {bt=bt+120000};
if (at<bt) {
// a is smaller
}
else
{
// a is not smaller
};
..should be cross-browser and time/format safe.
I tried something like this
var ts1="06:30:47 AM";
var ts2="01:10:47 PM";
var ds=new Date().toDateString();
var d1=new Date(ds+" "+ts1);
var d2=new Date(ds+" "+ts2);
if (!(d2>d1)){
alert("d1 should be less than d2");
}
Is there something wrong with this?
// specific formatter for the time format ##:##:## #M
var formatToMiliseconds = function(t){
t = t.split(/[:\s]/);
t = ((t[0] * 3600000) + (t[1] * 60000) * (t[2] * 1000)); // To ms
t = t + (/PM/i.test(t[3]) ? 43200000 : 0); // adjust for AM/PM
return t;
}
var time01 = formatToMiliseconds('06:30:47 AM');
var time02 = formatToMiliseconds('01:10:47 PM');
alert(time01 > time02); // false
allert(time01 < time02); // true
As a bonus, your time is now more compatible with the Date object and other time calculations.

Categories

Resources