JS Timezones not current - javascript

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();

Related

Moment and new Date() not displaying local time

I want to display the local date of the user, but nothing is working for me. It always returns the UTC time.
I have tried:
This returns UTC - also in here offset comes as zero.
let visitDate = moment.utc().format();
let offset = moment().utcOffset();
let visitDate1 = moment.utc(visitDate).utcOffset(offset)
This returns UTC
let visitDate = new Date()
let visitDate1 = moment(visitDate).local().format('MM-DD-YYYY hh:mm:ss');
This returns UTC
let visitDate = new Date()
let visitDate1 = visitDate.toLocaleDateString()
I have tried several methods, but it doesn't matter what I do, I always get UTC time. If I try on localhost then it displays the correct time, but once I host the page it displays UTC.
How can I transform to local?
moment().local() uses the timezone of the local machine, that's why it works in localhost
if you know it, I would specify the timezone:
moment.tz("America/Los_Angeles").format()
There seem to be several possible points of failure. I'll list the ones I think of below, and you can assess whether they're relevant to your setup.
1) The code that manipulates the date is executed on the server, not locally
Most of our Javascript code is written to execute in the user's browser, so that's the default assumption. If that assumption is wrong in this case, and the code is being executed on the server, then "local" means "on the server." Your server should be running with UTC time, which could produce the results you're seeing.
2) The user is running a browser set to UTC
If the browser you're using for testing is set to consider UTC as local time, it'd produce the results you're seeing. Since you're probably using the same machine for localhost and for testing, it's an unlikely source of the problem...but worth noting nonetheless.
3) Changing how the date is displayed does not change how the date is stored
Many of the tools we have for setting/changing the time zone affect how the date is displayed. However, Date objects in Javascript are stored using Unix Time (in milliseconds), which is UTC. When you create a Date object--even with a time zone specified--the behind-the-scenes representation will still be an integer (representing a number of milliseconds) and based on UTC. If you're checking the stored value rather than the displayed value, when you're testing, then there's a good chance you'll always see UTC. However, the work you're doing with the moment library should have the date formatted correctly. If you're checking the moment object, you should be seeing the time zone you expect to see.
If none of these three possible failure points applies to your context, then perhaps they spark an idea for you. (The third one, especially, feels like it might be on the right track even if it's not what's happening in your case.)

moment.js same time everywhere

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.

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.

How to find browser date time format [duplicate]

I have set a deadline in UTC, as shown below, and I'm wondering what exactly the toLocaleString() method will do to it on user's local machines. For instance, will it account for daylight savings if they are in a timezone that recognizes it? Or will I need to insert additional code that checks where the user is, and then fixes the displayed time?
http://javascript.about.com/library/bldst.htm
var deadline = new Date('5/1/2013 ' + "16:15" + ' UTC');
alert(deadline.toLocaleString());
In general, the answer is yes. JavaScript will represent the UTC value at the appropriate local time based on the time zone settings of the computer it is running on. This includes adjustment for DST. However, as others have pointed out, the details are implementation specific.
If you want a consistent output, I would use a library to format your dates instead of relying on the default implementation. The best library (IMHO) for this is moment.js. The live examples on their main page will give you an idea of what it can do.
UPDATE
If you are passing UTC values that you want converted to the correct local time, and that time falls into a period where the time zone rules are different than the current one - then the results will be invalid. This is crazy, but true - and by design in the ECMA spec. Read - JavaScript Time Zone is wrong for past Daylight Saving Time transition rules
We don't know what exactly the toLocaleString method does (§15.9.5.5):
This function returns a String value. The contents of the String are
implementation-dependent, but are intended to represent the Date in
the current time zone in a convenient, human-readable form that
corresponds to the conventions of the host environment’s current
locale.
But yes, most implementations will consider DST if it is active in the current local timezone. For your example I'm getting "Mittwoch, 1. Mai 2013 18:15:00" - CEST.
Will I need to insert additional code that checks where the user is, and then fixes the displayed time?
I think you can trust toLocaleString - the browser should respect the user's settings. If you want to do it manually, check out timezone.js.
As you use "UTC" the date itself will be UTC format, but the toLocaleString() takes client's locale into account, which means it'll return the date in string updated with all and every changes typical to client's regional and locale settings (DST, date/time format, etc).As JS documentation describes this: "The toLocaleString() method converts a Date object to a string, using locale settings.".If you want to avoid this, use the toUTCString() method instead.I'd also recommend reading the accepted solution for the question Javascript dates: what is the best way to deal with Daylight Savings Time? to avoid (at least, to try to avoid :) future issues related to JS, browsers and locales.Hope this helps!

Categories