I'm looking for replacing moment js functionality with plain Javascript - the project I need to re-work is not going to have moment.js available going forward. I have not worked with javascript Date in a while, so needs some good eyes on this. My question is two-fold.
Part 1: what I get with Date.UTC() is not the same as the value I get with moment.utc()
//original value: Mon Mar 04 2019 05:21:00 GMT-0800 (Pacific Standard Time)
var m = moment(date);
m.utc();
return m.format('YYYY-MM-DD[T]HH:mm:ss[Z]');
//m.format: 2019-03-04T13:21:00Z
This is my replacement for m.utc (it designers improvement):
var d = new Date(date);
var utcVal = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
var d2 = new Date(utcVal);
var sec = d2.getSeconds()<10? "0"+d2.getSeconds():d2.getSeconds();
var mm = d2.getMonth()<10? "0"+(d2.getMonth()+1):d2.getMonth();
var formated = d2.getFullYear()+"-"+mm+"-"+d2.getDate()+"T"+d2.getHours()+":"+d2.getMinutes()+":"+sec+"Z";
//d2 formated: 2019-03-3T21:21:00Z
I'd like to have something much cleaner than what I have above. Most glaring problem is that both the date and the hours are wrong. How can I fix this without usage of any other external libraries?
Part 2: I would like to confirm if what I already have for moment replacement is the right thing:
//value: 2019-03-04T13:21:00Z
var m = moment.utc(value);
m.local();
return m.toDate();
Here is my replacement for the above (it seems the .utc conversion is not used, .local is used instead):
var d = new Date(value);
return new Date(d.toLocaleString());
The above appears to be doing the right thing, but I wonder if there are edge cases I'm not thinking of.
For Part 1, you should look into the toISOString() method. Attach that to the Date object and it will return a string in the format you're looking for with a lot less work.
I could be misunderstanding, but seems as though toISOString would satisfy the requirement here:
var event = new Date('Mon Mar 04 2019 05:21:00 GMT-0800');
console.log(event.toString());
console.log(event.toISOString());
Related
I have this problem.
I have this date with this format
var datestring = "2017-10-30T15:03:10.933044Z";
If I write my code like this
var d = new Date(datestring);
I obtaine
Mon Oct 30 2017 16:03:10 GMT+0100 (ora solare Europa occidentale)
because there is one hour of a daylight in italy now. Nevertheless, I would like to have the same hour of 'datestring' (15, and not 16).
Could you help me?
thank you very much
According to ECMA-262, if you want to treat an ISO 8601 format UTC timestamp as local, just remove the Z. However, it will now represent a different moment in time if the local timezone is not GMT+0000.
Also, using the built-in parser is not recommended (see Why does Date.parse give incorrect results?), as some browsers will still treat it as UTC (e.g. Safari 11) or perhaps invalid. You should either write your own function to parse the string, or use a library. There are plenty of good parsing and formatting libraries available.
var s = '2017-10-30T15:03:10.933044Z';
var d = new Date(s.replace(/z/i,''));
console.log(d.toString());
Your input string is in ISO-8601 format. In this format, the Z at the end means the timestamp is UTC-based.
You can obtain a more human-friendly UTC-based string representation with the .toUTCString() method.
var datestring = "2017-10-30T15:03:10.933044Z";
var d = new Date(datestring);
var s = d.toUTCString();
console.log(s) // "Mon, 30 Oct 2017 15:03:10 GMT"
If you want the string in a specific format, then consider using a library like Moment.js.
toLocaleString() is deprecated but seems to lack replacement
I have a website where I store member post dates in this format: YYYY-MM-DD HH:MM:SS
The problem is that these dates are all stored with the timezone UTC and I want to convert these dates using JS to the users OS timezone. I know I could just ask users to input their timezone but I would like to try something new which require as little user interaction as possible. The goal of the site is to make a forum which is incredibly easy and straightforward to use.
I have almost gotten it to work the way I want but it currently only supports Chrome it seems like. This is not good enough since I plan on having a lot of users.
Since the timezone offset varies it is not good enough to only retrieve the current time offset which a lot of topics here seem to suggest. I want to accurately display for e.g. registration dates.
This is my current solution (timezone test only supports chrome as far as I can tell) it is also implemented on the whole website which is in beta.
https://ingsan.net/timezone/
Source code below
var d = new Date();
var tzName = d.toLocaleString('en', {timeZoneName:'short'}).split('').pop();
var cusid_ele = document.getElementsByClassName('timestamp');
for (var i = 0; i < cusid_ele.length; ++i) {
var timestamp = cusid_ele[i];
timestamp.innerHTML += " "+tzName;
t = new Date(timestamp.innerHTML);
usertime = t.toLocaleString()
timestamp.innerHTML = usertime;
}
I have used this site for years without asking but this time I seem to be unable to find a topic similar enough to mine.
The method I use which might be questionably is simply replacing objects inside the assigned class name. I plan to do other classes for other format outputs.
<p>Register date: <span class="timestamp">2016-01-31 20:12:55</span></p>
If you got a solution to this issue I would very much appreciate it. I am no professional and never went to any course but I have managed to make ingsan.net on my own. Help a humble student out ;)
If all you're doing is converting from UTC to the browser's local time zone, you do not need to actually try to figure out what time zone that is. Just be sure your input is clearly identified as UTC, and the default behavior of the Date object is to display values in the browser's local time zone.
var input = "2016-01-31 20:12:55";
var d = new Date(input + " UTC");
var s = d.toString();
The resulting string will vary by implementation and time zone, such as (a few examples):
"Sun Jan 31 2016 12:12:55 GMT-0800 (Pacific Standard Time)"
"Sun Jan 31 2016 15:12:55 GMT-0500 (Eastern Standard Time)"
"Mon Feb 01 2016 01:42:55 GMT+0530 (India Standard Time)"
"Mon Feb 01 2016 09:12:55 GMT+1300 (New Zealand Daylight Time)"
This will work in all browsers. The only problem is that you don't have control over the format of the output string. That's where toLocaleString can help, though as you pointed out - it's not necessarily implemented in all browsers. However, you seemed to think it was deprecated, and it is not. It's actually part of a newer specification (ECMA-402), which just is not widely implemented everywhere (yet).
You have other options though. You could build the output string yourself, like this:
var z = function(x) {return x < 10 ? '0' + x : x};
var s = d.getFullYear() + '-' + z(d.getMonth() + 1) + '-' + z(d.getDate()) + ' '
+ z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
Of course you could figure out how to adjust to 12 hour format, use different separators, different date-field ordering (YMD vs DMY vs MDY), etc.
Or, you could just use a library such as moment.js which is already equipped for that.
var input = "2016-01-31 20:12:55";
var m = moment.utc(input).local(); // parse as UTC, then switch to local mode
var s = m.format(); // use any of the format parameters you wish
I'm using moment.js to find a time in different timestamp.
I wrote a simple javascript:
$(function () {
var timestamp = 1443556318; //GMT Tue, 29 Sep 2015 19:51:58 GMT
var today2 = moment.unix(timestamp).tz('America/New_York').toString();
today = new Date(today2);
alert(today2);
alert(today);
var hh = today.getHours();
alert(hh); //why it shows me 21 instead of 15?
});
and seems like this line today = new Date(today2); does not work properly.
Can you help me with that?
http://jsfiddle.net/b8o5cvdz/3
It doesn't work because, you use the following constructor
new Date(dateString);
where the
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
If you want to all the possible constructors, please have a look here.
How can I parse a simple date string and let JavaScript know that it's actually a UTC date? Currently, if I do new Date('2015-08-27') it converts it to my timezone.
You can do append 'T00:00:00.000Z' to make the time zone specific (Z indicates UTC)
new Date('2015-08-27' + 'T00:00:00.000Z')
Note that new Date('2015-08-27') is treated differently in ES5 (UTC) vs. ES6 (Local), so you can't expect it any correction to be work consistently if you were planning to to hard code it (i.e. don't do it)
Also, do note that your console.log might show you the local time corresponding to the UTC time the expression evaluates to (that tends to throw you off a bit if you are expecting UTC to be at the end for expression that evaluate to UTC times and your local time zone at the end for those that evaluate to your local time). For instance
new Date('2015-08-27T00:00:00.000Z')
could show
Thu Aug 27 2015 1:00:00 GMT+100
which is the same as
Thu Aug 27 2015 00:00:00 UTC
In some cases, while other solutions don't work, adding GMT will help:
new Date('July 11, 2022, 16:22:14 PM' + ' GMT')
This might be obvious to most, but I got stumped for a few seconds because my string already had hh:mm:ss, so it required a little bit of string manipulation.
var d = '2022-09-14 13:20:31';
d = d.split(' ').join('T')+'Z';
var date = new Date(d);
console.log(date);
This version is more verbose, but feels sturdier to me.
var d = '2022-09-14 13:20:31';
var [yyyy, mm, dd, hh, m, s] = d.split(/[^\d]+/);
var date = new Date();
date.setUTCFullYear(+yyyy);
date.setUTCMonth(mm-1);
date.setUTCDate(+dd);
date.setUTCHours(+hh);
date.setUTCMinutes(+m);
date.setUTCSeconds(+s);
console.log(date);
Here is what I would do.
var current = new Date();
var utcDate = new Date(current.getTime() + current.getTimezoneOffset() * 60000);
I'm retrieving data from a JSON feed using jQuery and as part of the feed I'm getting 'datetime' attributes like "2009-07-01 07:30:09". I want to put this information into a javascript Date object for easy use but I don't believe the Date object would recognize this kind of format if I simply plugged it into the constructor. Is there a function or maybe a clever trick I can use to quickly break down this format into something the Date object can recognize and use?
The "date" attribute you are retrieving from that webservice is not a real Date, as it is not a recognized date format.
The easiest way to handle it as a Date object would be to replace the empty space with a "T":
var receivedDate = "2009-07-01 07:30:09";
var serializedDate = new Date(receivedDate.replace(" ", "T"));
alert(serializedDate);
This is not the most correct, as it is not handling timezones, but in most cases will work.
See this and this.
input = "2009-07-01 07:30:09";
var res = input.match(/([\d\-]+) (\d+):(\d+):(\d+)/);
date = new Date(Date.parse(res[1]));
date.setHours(res[2]);
date.setMinutes(res[3]);
date.setSeconds(res[4]);
console.log(date);
Edit: My original answer was
t = new Date(Date.parse("2009-07-01 07:30:09"));
which did not throw any error in chrome but all the same incorrectly parsed the date. This threw me off. Date.parse indeed appears to be quite flaky and parsing the complete date and time with it is probably not very reliable.
Edit2: DateJS appears to be a good solution for when some serious parsing of text to date is needed but at 25 kb it is a bit heavy for casual use.
var str="2009-07-01 07:30:09";
It depends on the time zone,
and if the date string has subtracted 1 for the month.
If it is GMT time, and the 07 means July and not August:
var str="2009-07-01 07:30:09";
var d=new Date(), time;
str=str.split(/\D0?/);
str[1]-=1;
time=str.splice(3);
d.setUTCFullYear.apply(d,str);
d.setUTCHours.apply(d,time)
alert(d)
/* returned value: (Date)
Wed Jul 01 2009 03:30:09 GMT-0400 (Eastern Daylight Time) or local equivilent
*/
This may be a bit cumbersome, but the JavaScript Date object will take an argument list of YYYY,MM,DD,HH,MM,SS. Parse out the date value and pass it to a Date constructor, e.g.
var splitDT= '2009-07-01 07:30:09'.split(' '); // ['2009-07-01','07:30:09']
var d= splitDT[0].split('-');
var t= splitDT[1].split(':');
alert( (new Date(d[0],d[1],d[2],t[0],t[1],t[2])) );
Bah. Had to use the array index values instead. Yeah, that's a mess. But it works.