moment.js same time everywhere - javascript

I was writing a chrome extension this morning and the everything seems fine.
However by night time I had noticed that the time being displayed is wrong.
At first I thought it was a code problem but after going onto their site it seems like every single places the time were all displaying my local time.
Is anyone experiencing this same problem?
Or should I consider changing the library all together...
I've recorded a video here
http://youtu.be/g6n6nXJt_uU
function setClock()
{
now = moment.tz(moment.tz().format("MM/DD/YYYY hh:mm"),
"EST").format("MM/DD/YYYY hh:mma");
document.getElementById("time").innerHTML=now + " NYC";
}
console.log(moment.tz("EST")._d);
console.log(moment()._d);
setClock();
setInterval(setClock,1000);
CodeOutputHere

Regarding your code:
You should not use time zone abbreviations like EST for this purpose, since time zone abbreviations are often ambiguous. If you're looking to set US Eastern Time, then you should be using the IANA time zone identifier of America/New_York.
EST only exists in the tzdb for backwards compatibility purposes. Arguably, it should be left out of the moment-timezone data.
Calling moment.tz() without any argument is not recommended. You should just call moment().
Your code appears to be formatting a moment, then parsing it into another moment, then formatting it out again. There's no reason to jump through so many hoops.
You should not use the _d property. That is meant to be internal to moment.js. (It should probably be hidden by closure, but it's not). Instead, use .format() or one of the other public functions.
Ultimately, I think you are simply after:
var now = moment().tz('America/New_York').format("MM/DD/YYYY hh:mm");
I highly suggest you re-read the moment-timezone and moment.js documentation.
Regarding the moment-timezone web site with the map - you're correct that there's currently a bug with the demonstration web site. It is not a bug with the library itself. I'll investigate and report that to the moment team.

Related

Does momentjs have something similar to joda-time's localDate? If not, is it best to use .startOf?

In the joda-time library (and I assume Java 8's new time library), you can ignore times and time zones: https://www.joda.org/joda-time/apidocs/org/joda/time/LocalDate.html
I would prefer to avoid having times factor in in my small app. I just want the user to see their local date. Is there a momentjs equivalent to localdate? If not, would the best workaround be to use .startOf()? Thanks.
Edit: Just to be clear, this is not a formatting question.
"By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc()"
As explained here.
moment().format(); // 2013-02-04T10:35:24-08:00 (local date)
moment.utc().format(); // 2013-02-04T18:35:24+00:00 (UTC date)

Enforce timezone for angular.js application

I'd like to use one single timezone for an angular.js application. I'm aware that angular.js currently uses browsers timezone settings for date formatting, but I'd like to override this setting so that I can enforce a specific timezone for a user so that it doesn't depend on a browser settings.
It is a business application in question so there is no need for user specific timezones. Everything happens in a company's specified timezone and this is why I'd like to enforce it for every user. Data is saved in UTC, but it needs to be shown in company timezone for every user without depending on user location/locale/browser settings.
Is there any way I can accomplish this that anyone is aware of? And if there is, it'd be greatly appreciated to point me to correct way to do it :) So far I've had zero luck with it.
You can use a library such as timezone.js, or moment.js. I've used timezone successfully, and I've heard moment.js works pretty well. You'll likely want to make an injectable factory..
angular.module('date', [])
.config(function () {
timezoneJS.timezone.zoneFileBasePath = '/tz';
timezoneJS.timezone.init();
})
.service('dateConverter', function () {
return {
toDisplayDate: function (utcDateIn) {
return new timezoneJS.Date(utcDateIn, 'America/Los_Angeles')
}
}
});
That's just off the top of my head, but it's an example of what you'll probably have to do - convert dates from native JS to the library dates.
Sorry, but it's not possible to change the time zone behavior of the JavaScript Date object. It will always use the time zone of the computer that it's running on.
The best you can do is work around it with one of the libraries listed here. Stephen's answer shows how you can integrate one of them in to Angular.
Also, I'd consider very carefully when you say "there is no need for user specific timezones". Sometimes, that is the case, but very rarely. Often, companies have locations in multiple time zones, or they have employees that travel, or they interact with customers or partners that are in different time zones.
Besides, if what you say is true - that users are always in the single time zone of the company, then wouldn't that already be the local time zone for their computer? If so, then there's not much to do.
If you have users in other time zones, but you wish them to use the company's primary time zone, then that would be a case that would require one of these libraries. But consider carefully the impact of that. Depending on how far away a user is, even their current date might be different than the company's date.

JS Timezones not current

I have just created a blog script, but when I add a comment.
The timestamp in the database is 2014-07-29 18:55:00 even that the clock on my PC is 2014-07-29 20:55:00.
So I would like to change the time according to the timezone.
So I tried with this code (where timestamp is 2014-07-29 18:55:00):
var UTC = moment.tz(timestamp, "UTC");
timestamp = UTC.clone().tz(timezone).format('YYYY/MM/DD H:mm:ss');
Note: window.timezone is set using the following code:
var tz = jstz.determine();
var timezone = tz.name();
The time I want to get out is 2014/07/29 20:55:00, but I get this out: 2014/07/29 17:53:47
I am using the following libraries for this above code:
https://bitbucket.org/pellepim/jstimezonedetect
http://momentjs.com/timezone/
http://momentjs.com/
Hope that someone understands whats going on.
NOTE: I live in Europe/Denmark which have the timezone UTC/GMT +2 hours
In addition to script, moment-timezone requires data to function. If you don't have the data loaded, in version 0.1.x it will use the local time zone - as if you just called moment() without any tz specified. This has been fixed for the upcoming 0.2.0 release, such that it gives an error instead of silently doing the wrong thing.
Normally, you could use the data builder to just provide data for the time zones you were interested in. However, it is currently offline because the format of the data changed in the last release and the author has not yet had time to complete the required updates.
In the meantime, you can use one of the "data-included" versions, downloadable at the top of the main page - for example, use moment-timezone-2010-2020.js instead of just moment-timezone.js.
Also, you since you're using jsTimeZoneDetect - you should test the value returned by jstz.determine() to make sure it is indeed the time zone you are expecting. The +2 offsets are notoriously difficult to test for. See some of the known issues.
You could set the timezone
moment().tz("Europe/Denmark").format();

Creating a time with a specific time and timezone in momentjs doesn't appear to work as per the doco

I am trying to set an arbitrary date/time in momentjs with a specific timezone such that the timezone is stamped on the object with the original hh:mm values.
From the doco at http://momentjs.com/timezone/docs/ - this is definitely possible.
However, from further testing (see http://jsfiddle.net/patsimon/SFf5V/2/), things don't quite work as they are document too.
From the doco:
moment.tz("2013-11-18 11:55", "America/Toronto").format(); // "2013-11-18T11:55:00-05:00"
From my running code:
moment.tz("2013-11-18 11:55", "America/Toronto").format(); // "2013-11-17T20:55:00-05:00"
This will obviously differ for others who run this from a timezone different to mine (+10:00) - but I was led to believe that the whole point of this method was to only honour the timezone explicitly provided?
This is a bug and has already been reported here:
https://github.com/moment/moment-timezone/issues/57

Javascript date object in different locale and timezone

I need to write a web application that show events of people in different locale. I almost finished it, but there're 2 problems with date:
using date javascript object, the date depends on user computer settings and it's not reliable
if there's an event in a place with dfferent timezone respect user current position, i have to print it inside (). Is it possible in javascript to build a date object with a given timezone and daylight settings?
I also find some workaround, such as jsdate and date webservices, but they don't overcome the problem of having a javascript object with the correct timezone and daylight settings (for date operation such as adding days and so on).
A couple of things to keep in mind.
Store all event datetimes in UTC time
Yes, there is no getting around this.
Find out all the timezones...
...of all the users in the system. You can use the following detection script: http://site.pageloom.com/automatic-timezone-detection-with-javascript. It will hand you a timezone key such as for example "America/Phoenix".
In your case you need to store the timezone together with the event, since a user may switch timezone - but the event will always have happened in a specific one. (argh)
Choose your display mechanism
If you want to localize your event dates with Javascript, there is a nifty library for that too (which can use the keys supplied with the previous script). Here: https://github.com/mde/timezone-js.
with that library you can for example do this:
var dt = new timezoneJS.Date(UTC_TIMESTAMP, 'America/New_York');
or
var dt = new timezoneJS.Date(2006, 9, 29, 1, 59, 'America/Los_Angeles');
where UTC_TIMESTAMP for example could be 1193855400000. And America/New_Yorkis the timezone you have detected when the event took place.
The dt object that you get from this will behave as a normal JavaScript Date object. But will automatically "correct" itself to the timezone you have specified (including DST).
If you want to, you can do all the corrections in the backend - before you serve the page. Since I don't know what programming language you are using there, I cannot give you any immediate tips. But basically it follows the same logic, if you know the timezone, and the UTC datetime -> you can localize the datetime. All programming languages have libraries for that.
You're missing the point of a Date object. It represents a particular point in time. As I speak, it is 1308150623182 all over the world. Timezone only comes into play when you want to display the time to the user. An operation like "adding a day" does not involve the time zone at all.
One possibility might be to use UTC date and time for everything. That way, there is nothing to convert.
Another is to have your server provide the time and date. Then you don't have to depend on the user to have it set correctly, and you don't have to worry about where your user's timezone is.
Use getUTCDate(), getUTCHours(), ... instead of getDate(), getHours(),...
getTimetoneOffset() could be useful, too.

Categories