Deal with timezones in JS from UNIX timestamp - javascript

I'm currently writing a small messaging app for global usage. I'm going to store the UTC timestamp of the message. I need to display the message to the user using AJAX, so i need to convert the UNIX timestamp to the users local time. I know how to get the timezone offset, but i'm afraid that it will be a little bit inaccurate and i need accuracy even in seconds (to display times like: 34 seconds ago). Which is the most accurate way to solve this?

Why not calculate the local date locally? Constructing a date with new Date(millisecondsSinceEpoch) locally and then calling toTimeString() (or whatever) should show you the local time:
new Date(milliseconds).toTimeString()

var d = new Date((new Date(1390312399000)).toUTCString());
Where the timestamp is the stored UTC timestamp.

Related

sending javascript date object to server without adjusting for time zone difference

Is there a way to send data from the client to a server without adjusting the time to account for the time zone difference between the client and server?
I have an angular app with a nodejs server. When I send a date from a form to the server via an HTTP request and log the date on the server, the date changes to the time in the time zone of the server.
I'd like to send the date object back and forth without it changing.
I always use http://momentjs.com/ when dealing with javascript dates. When a date object is created the systems timezone is used, so you'll always have to adjust for the offset. The easiest solution is to do one of the following
use a string and parse it
use moment().format() with a custom format
use UTC on the client and server
use ticks or unix epoch
There really isn't a great solution, you just need to be consistent.
Use milliseconds .
let now = new Date();
let time = now.getTime();
time contains number of milliseconds in UTC timezone always. In the server you can convert milliseconds to date . This way you dont need to worry about timezones.
According to MDN Javascript Date objects are constructed using UTC.
You can send the date object back and forth without ever changing it, it will simply be interpreted relative to the 'locale' of wherever it is being used.
If you'd like to maintain the local date and time irrespective of location (between different client and server locations) you'll probably need to pass along the locale of the Date as well as the Date itself.
A way to do this is to format your Date as a string in ISO 8601 format with a time offset (like +0100.)
That way you'll get both the local time and the offset used for every time.
You can construct it by hand using the Date.prototoype.toISOString method but that will still be relative to UTC.
Here's another Stack Overflow question on how to get the correct offset yourself.

Moment.js - Converting UTC To Eastern Time

I am using moment-timezone.js in order to convert UTC time to America/New_York via node.js. I am doing this like so:
var moment = require('moment-timezone');
moment.tz.add('America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0');
var now = new Date().toISOString();
now = moment(now).tz("America/New_York").toDate();
This seems to work fine on my local machine, but when I run it on AWS Lambda, the now time is still being outputted as UTC.
Am I doing something wrong here? I really don't want to have to use an API just to get the accurate New York time. Daylight savings is the biggest challenge here. Thanks!
First, install moment timezone and install all of the timezones by using timezone-with-data.js or specifically only load the timezones you need
If you have a date that you know is in UTC and want to convert it to Eastern time, use the moment.utc() function to actually parse the UTC datestring. Then when you call .tz() on it will properly convert:
moment.utc(date_string).tz("America/New_York")
If you simply do moment(date_string).tz("America/New_York") the time gets parsed in your local timezone by default, and it will not adjust the date.
The way I figured this out was to do:
var now = ((moment(Date.now()).utcOffset('-0500').format('x'));
//Parse it into native JS object:
now = new Date(parseInt(now));
I want to point something out though that I hope will save someone the days of time this burdened me for. My main issue was that Amazon Lambda was providing time in UTC, no matter what I was doing. The fix for this issue was to simply set the Node TZ environment variable:
process.env.TZ = 'America/New_York';
Eastern Standard Time (EST) is 5 hours behind Coordinated Universal Time (UTC).
With moment.js, you can subtract 5 hours from UTC timezone.
moment.utc().subtract(5, 'hours').format("YYYY-MM-DD HH:mm:ss.SSS")
Or
If you are willing to add another library like moment-timezone. You can just use:
moment().tz("America/New_York").format("YYYY-MM-DD HH:mm:ss.SSS")

Convert set date to user's local time automatically

I am creating an application where I have a pretty big set of dates and times, and I need to display these in the user's local time and date. All set dates and times are in BST; so for example 08-24-2014 16:00 BST = 08-24-2014 11:00 EST. Now, before coming here I spent good 3-4 hours looking for an answer but if anything, I got more confused. Is there any way, to convert a set of BST dates and times to the user's local settings automatically without them setting the time zone etc?
p.s.: I have two ideas in mind but I don't know if they would work nor how to execute them.
1) Get and change the BST date and time and convert it to a unit of measurement; get and change the user's local date and time and covert it to the same unit of measurement as above, calculate the difference in the new measurement, and convert that to the user's local time.
2) Use GeoLocation to find the user's date and time/ time zone and; convert the BST to whatever the GeoLocation spits out.
you can get the users machine timezone in javascript:
var currentDate = new Date();
var currentTimeZoneOffsetInHours = currentDate.getTimezoneOffset() / 60;
see documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
having the offset you can add it to your values
there is a javascript library Moment.js which allows you to query daylight saving values for specific dates and timezones.
because all your dates are in british summer time. first query if a date is in british winter time with isDSTShifted(). and subtract() an hour.
convert the date to another timezone

Is there a simple time to get a timezone from a given time?

I need to get a timezone from a time, date is not important, but daylight savings is.
something like:
timezone = function("15:00");
Is there a simple way to do this?
I dont think you can get the timezone from the time but you might get some help from Date.prototype.getTimezoneOffset()
The getTimezoneOffset() method returns the time-zone offset from UTC,
in minutes, for the current locale.
Example:
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
No, of course not. Think about it, you're passing 15:00 to that function, presumable denoting it's 3PM. But in what timezone is it 3 PM? No way of knowing. It's like me saying it's quarter to, without saying what hour it's quarter to to.
The only way you can get a timezone in JS is by using the Date object, but that just shows the timezone of the machine on which your code is running, nothing about the TZ that "created" the time you're processing.
Also note that daylight saving isn't a global phenomenon, quite the contrary. AFAIKT, there isn't a single time-zone where DST has always been in place...
In order to get TimeZone information you need more than a Date (and an offset). You need a location.
Javascript does not know the location that it resides in but it does know the current offset from UTC. That is different than a Time Zone. The daylight savings time issue play havoc with this key difference.
This has posed problems when dealing with server applications that know their timezone and report dates as being in a specific Time Zone.
My rule of thumb has been fairly simple in this regard.
Always use Long or long (a 64 bit number) to store, pass and process dates times or intervals, only convert to Date, Calendar or DateTime objects when interacting with people.
Once you have a date object, such as with new Date(), you can use .getTimezoneOffset() to get the number of minutes between the date's object and UTC, which is timezone information you can use.

javascript timezone converter

I need a way to convert times in the future to different timezones without relying on the user's computer time.
At registration time, the user supplies his timezone. When he logs in, I calculate the offset in minutes between the UTC time and his time and inject that offset into the page so that a javascript function can do the conversions. Something like this:
var TheUTCTime = new Date(UserTime.getTime() - TimeZoneOffsetInMinutes * 60000);
and like this for the other way around:
var TheUserTime = new Date(UTCTime.getTime() + TimeZoneOffsetInMinutes * 60000);
This works really well to convert times as long as the offset doesn't change. For instance, because of daylight saving, between US EST and UTC, there's a difference of 300 minutes or 360 minutes depending on the month in the year.
My functions work well to convert today's date but I'd like something that can 1) do the same thing for any day of the year and 2) doesn't depend on the user's internal clock or timezone.
How could I do this?
Thanks.
My functions work well to convert today's date but I'd like something that can 1) do the same thing for any day of the year and 2) doesn't depend on the user's internal clock or timezone.
If you want to convert another UTC time into the user's local time, you have to know their time zone. That's pretty much the definition of a time zone: a mapping between UTC and local time (or equivalently, between UTC and the offset from local time).
As you've seen, getting the current offset isn't enough, because of daylight saving transitions (and any other changes to time zones - they vary more than you might expect).
Basically there's no way round this: you will have to ask the user for their time zone. You can make a good guess based on the current offset from UTC and possibly geocoding their IP address, but you'll have to confirm it with them. (For example, they may be on a trip or something, and not in their "home" time zone.)
To don't depend on the user's clock timezone, I think the best approach is to do conversions in the server side.
There's a good question here in the SO that covers daylight saving time and javascript Date object: Daylight saving time and time zone best practices

Categories

Resources