Time Zone Sensitive Date and Time Display in Web Applications? - javascript

I am looking for recommendations on displaying times in a web application in a time zone other than the user's current time zone.
We store our dates/times in UTC/GMT in the database, so it is not an issue to format the time for UTC/GMT or the user's current time zone. However, in other situations we need to display the time from the point of view of an arbitrary time zone (i.e. every date/time on this page is in Eastern, regardless of whether or not the user is in West Coast, Central, Eastern, etc.).
In the past we have stored offsets or time zone info, then done the calculations in server code in .Net or else we have done some client-side manipulations in javascript that I would prefer to avoid, since it all becomes very dependent on javascript and the user's browser. I'd like to know the best way to do this in a more client-side/MVC type application.
Here is an example:
Date stored in db: 1302790667 (Thu, 14 Apr 2011 14:17:47 GMT)
Converted date displayed for a client in Central time zone: Thu Apr 14 09:17:47 2011
Date I actually want to display, always in Eastern time zone: Thu Apr 14 10:17:47 2011
In the above example, it's easy to get the time in UTC (#1) or the user's current time zone (#2) but it is more difficult to get #3. My options seem to be:
Store offsets or time zones in the db and do calculations on the client - this is what we've done in the past with .Net but it seems even messier in client side code is the path we are currently trying to avoid.
Do the conversion on the server and send down a full date for display to the client - client receives a string ("Thu Apr 14 10:17:47 2011"). This works but it's not very flexible.
Do the conversion on the server, break it into parts and send those down to the client, then put them back together. ("{DayOfWeek:Thu, Month:Apr, Day:14, Hour:10, Minute:17}"). This gives us the correct data and gives us more flexibility in formatting the date but it feels a little wrong for this scenario.
Any other options ideas? How do others handle similar situations? Thanks.

Our results:
I tried out a few libraries like Datejs, MS Ajax, etc. and I was never very happy with them. Datejs didn't work at all in a few of my test cases, is not actively maintained, and seemed to focus a lot on syntactic sugar that we don't need (date.today().first().thursday(), etc.)
We do use jQuery for some basic date/time parsing.
I came across a lot of "roll-your-own" client-side date conversion "hacks", most of which only addressed the conversion to UTC, started off working fine, and then eventually fell apart on some edge case. This one was the 90% solution for a lot of standard UTC conversion but didn't solve our "arbitrary timezone" issue.
Between the code complexity the conversion routines added and the bugs they seemed to cause, we decided to avoid client side date processing most of the time. We do the date conversions on the server with our existing date handling routines and pass the formatted dates or info down as properties to be used by the view. If we need a separate date, we just add another property. There are usually only a few properties that we need at a time (i.e. EventDateUTC, EventDateLocal, EventDateAlwaysAustralia, and EventDayOfWeek).

I offer the suggestion that you look into the Datejs library. It offers a bunch of extensions to basic JavaScript date manipulation, including a "setTimezone()" method and flexible ways to convert a date into a formatted string for display.
I usually hesitate to suggest libraries when their use is not explicitly allowed for in questions, but Datejs isn't very large and it's pretty solid (even though it's called an "alpha" release). If you'd prefer not to rely on something like that, you might want to look at it anyway just to see the basics of how its extensions were implemented.

Related

How do I get the result of javascript new Date().getTimezoneOffset() transferred to C# backend?

See the title: for the solution I'm working on, I need to get the current timezone offset (from the client, running javascript/jQuery) and use it in backend C# code.
The question is rather similar to the one asked here, but there are a few differences - the main one being that I am pretty sure that the time on the client computer won't be tampered with. So new Date().getTimezoneOffset() will do just fine.
I cannot read the value upon submitting a form since the user is not working in a form: after the user has logged in, among the items that are visible on the screen is a table with data entered by the user or by other users. This data contains UTC datetimes that have to be adjusted according to the client's timezone. C# code is responsible for retrieving and formatting the data - hence my question.
What would suffice, is storing the value somewhere so that C# can read it when necessary. But I don't think that can be done as well. What would be the approach here?
Thanks in advance!
Your suggested approach is flawed in that the current offset from the client's browser is only going to apply to the current date and time. In reality, time zone offsets change over time within a given time zone. You cannot just take a singular offset from one point in time and expect to use it to convert other dates and times to the same time zone. Instead, you need to use the string that identifies the time zone, not an offset from that zone.
As an example, consider the Eastern time zone in the United States. For part of the year, it uses UTC-5, and we call it Eastern Standard Time (EST). In another other part of the year, it uses UTC-4, and we call it Eastern Daylight Time (EDT). This time zone is identified by either the IANA time zone ID "America/New_York", or the Windows time zone ID "Eastern Standard Time" (which covers the entire zone, both EST and EDT despite its wording).
So, break this problem apart into a few steps:
In JavaScript, identify the users's IANA time zone (America/New_York):
If you are targeting modern web browsers, you can call this function:
Intl.DateTimeFormat().resolvedOptions().timeZone
If you need to support older web browsers, you can use jsTimeZoneDetect, or moment.tz.guess() from Moment-Timezone.
Send that string to your web server through whatever mechinsm you like (form post, XHR, fetch, etc.)
In your .NET code, receive that string and use it to reference the time zone and do the conversion. You have two options:
You can use Noda Time, passing the IANA time zone ID to DateTimeZoneProviders.Tzdb as shown in the example on the home page.
You can use .NET's built-in TimeZoneInfo object. If you're running .NET Core on non-Windows systems (Linux, OSX, etc.) you can just pass the IANA time zone ID to TimeZoneInfo.FindSystemTimeZoneById. If you are on Windows, you'll need to first convert it to a Windows time zone ID ("Eastern Standard Time"). You can use TZConvert.GetTimeZoneInfo from my TimeZoneConverter library.
Once you have either a DateTimeZone from Noda Time, or a TimeZoneInfo object, you can use the methods on it to convert UTC values to local time values for that time zone. Each of these will apply the correct offset for the point in time being converted.
I'll also say, many applications simply ask the user to choose their time zone from a dropdown list and save it in a user profile. As long as you're storing a time zone identifier string and not just a numeric offset, this approach is perfectly acceptable to replace steps 1 and 2 above.

How to maintain Timezone

My client is in india and server in USA . If user submit his post from india it get stored in USA server so when i display post submit time to user it is as per USA time . I want to show it as per clients timezone
The simplest way to handle timezones is to work with Epoch time behind the scenes, and translate it to the user's preferred timezone on render (or with client-side code).
Epoch time is the number of seconds since it became 1 January 1970 in London. For example, right now the time is 1483130714. This means we've got one simple number, that can be effortlessly compared and sorted, to represent precise moments without needing to care about dates, timezones, locales and their frustrating details. Virtually all languages in popular use have the ability to parse these numbers into their own timestamp values. In JavaScript, you can do this with new Date(1483130714). You'll get a date object and you can then present that however you like (eg with toLocaleString).
If you don't use Epoch time, you'd want to use UTC, the next-best thing. The important thing is to store in a consistent universally-understood format and then translate it to the user's preferred form as needed.
You need to store date in UTC and then convert it as per browser culture and timezone. So store all dates in UTC and depending on browser culture you can add offset, this could be tricky if user sets wrong culture and time.

Print the time for a given location

Supposing I have
a date (i.e. an UTC timestamp),
a location (e.g. "Paris") that I may encode as I wish (and which isn't the one of the browser),
no permanent internet access
then what can I do if I want to format my date for this specific location, correctly dealing with daylight saving time when/if it occurs ? I'd prefer a standard based solution. I expect the solution to either include a reliable table of some sorts or to call some browser/computer magic.
Of course, as the offset is dependent of the moment, I can't just store the location as an offset.
Here are 2 points which ease the problem :
I won't deal with dates before 2010
if some country decides to change the rules regarding its timezone, it's acceptable for me to release a new code/library
Have a look at moment.js which support localization in a pretty nice way as well as time zones.
For the location issue, I would say you will have a really hard time solving that without an Internet connection. I would say the only way to solve it is to have your users enter a country (and maybe time zone) manually.

Get GMT time difference between now GMT and 1 January 2013 gmt

I am trying to store the time as a difference between 1 jan 2013 and the moment i save it on the database. It is definitely smaller than the standard of making it relative to 1970 ;) both in storage and because i am sending it clientside.
As I am going to do a getRelativeTime() quite a lot, I am looking for simplicity. I might change it from 1 jan 2013 to the date of server launch which is the 1st of a month in 2013 :D
I am keeping client and serverside track in GMT and it is on a nodejs server, the server is unknown. From what I researched, there are some solutions, but many call them incorrect due to this and that :|
To offer a valid answer to your question:
var ms = new Date() - Date.UTC(2013,0,1);
But PLEASE do not do this.
You will end up confusing anyone that uses your system (developers, api clients, database folks, etc.)
You will not be saving as much in terms of bytes as you think. JavaScript Number types are always 64 bits (8 bytes) in memory, see here. How much you might save in the database is very dependent on your database platform, but for example, the MySQL DATETIME type takes 8 bytes, while the TIMESTAMP type takes only 4. The range of a TIMESTAMP is much smaller, reference here and here.
You will probably encounter negative numbers frequently, if your app works with dates before your epoch. They will work, but they could be a source of confusion. If someone isn't aware of your adjusted epoch, they could produce a date that looks valid, but is supposed to mean something different.
You will also throw out any potential for using many great libraries that expect dates to work a certain way. You could convert to and from your custom date to a standard one, but do you really want to constantly wrap and unwrap those values? Probably not. Even libraries like moment.js that use their own types, do so by extending or encapsulating the standard data types. Compatibility is a much higher concern than byte space.
There are a lot of things wrong with JavaScript dates, but the choice of 1/1/1970 as an epoch was a good thing. Just because you can do something, doesn't mean that you should.
Also, consider that disk space is usually the least expensive component to running an application. Even with millions of records, you are likely to save a few dozen megabytes at most. Let's just error on the high side and say you save 200 MB with this clever hack. Amazon's top-tier provisioned IOPS cloud storage is $0.125 per GB per month. Congratulations, you've saved $7.68 over the entire year.
You are trying to normalize the value of epoch time? Epoch time as such gives in positive integer values. ain't it? 1356998400 is the amount of data you want to normalize.

Localize dates on a browser?

Let's say I have a date that I can represent in a culture-invariant format (ISO 8601).
I'll pick July 6, 2009, 3:54 pm UTC time in Paris, a.k.a. 5:54 pm local time in Paris observing daylight savings.
2009-07-06T15:54:12.000+02:00
OK... is there any hidden gem of markup that will tell the browser to convert that string into a localized version of it?
The closest solution is using Javascript's Date.prototype.toLocaleString(). It certainly does a good job, but it can be slow to iterate over a lot of dates, and it relies on Javascript.
Is there any HTML, CSS, XSLT, or otherwise semantic markup that a browser will recognize and automatically render the correct localized string?
Edit:
The method I am currently using is replacing the text of an HTML element with a localized string:
Starting with:
<span class="date">2009/07/06 15:54:12 GMT</span>
Using Javascript (with jQuery):
var dates = $("span.date", context);
// use for loop instead of .each() for speed
for(var i=0,len=dates.length; i < len; i++) {
// parse the date
var d = new Date(dates.eq(i).text());
// set the text to the localized string
dates.eq(i).text(d.toLocaleString());
}
From a practical point of view, it makes the text "flash" to the new value when the Javascript runs, and I don't like it.
From a principles point of view, I don't get why we need to do this - the browser should be able to localize standard things like currency, dates, numbers, as long as we mark it up as such.
A follow up question: Why do browsers/the Web not have such a simple feature - take a standard data item, and format it according to the client's settings?
I use toLocaleString() on my site, and I've never had a problem with the speed of it. How are you getting the server date into the Date object? Parsing?
I add a comment node right before I display the date as the server sees it. Inside the comment node is the date/time of that post as the number of milliseconds since epoch. In Rails, for example:
<!--<%= post.created_at.to_i * 1000 %>-->
If they have JS enabled, I use jQuery to grab those nodes, get the value of the comment, then:
var date = new Date();
date.setTime(msFromEpoch);
// output date.toLocaleString()
If they don't have JS enabled, they can feel free to do the conversion in their head.
If you're trying to parse the ISO time, that may be the cause of your slowness. Also, how many dates are we talking?
Unfortunately, there is not.
HTML & CSS are strictly used for presentation, as such, there is no "smarts" built in to change the way things are displayed.
Your best bet would be to use a server side language (like .NET, Python, etc.) to emit the dates into the HTML in the format you want them shown to your user.
It is not possible to do this with HTML, it has no smart tags that can make any kind of decisions like this. It is strictly presentational. I do wonder, though, if HTML5 perhaps has a tag for something like this...
Anyways, the way I see it, you have 3 options:
Stick to the Javascript way. There's questions with more details on it on this website, such as How do I display a date/time in the user’s locale format and time offset? and How can I determine a web user’s time zone?
Try to use geolocation. That is, your server side script fires off a request to one of the many geolocator services out there on the user's first page visit to try and guess where the user is. The downside of this is that it will be wrong about 10% of the time, so it's not that much better than the market share Javascript is going to get you.... (all in all, then, not a very good method...)
Ask the user! You will see that most websites that want to display a tailored experience for you will ask you this sort of thing because it's just not possible to know. As a neat fallback, you could wrap the question around <noscript> tags so you only ask those with Javascript disabled while offering the Javascript experience to those that have it.
Dojo has some pretty good localizations for dates and currencies. Using this method also allows you to pick different formats (e.g.: short date vs long date) and force locales.
The language and the user's locale should be sent on the HTTP header. You can use those to create the correct date format server-side to be displayed to the user. However, this is often undesirable because many users completely ignore their locale settings in their OS and/or browser. So, you may be feeding USA style timestamps to New Zealanders.
I liked the trick posted in the comment above, but it sounds like a QA headache, since you could be dealing with a large number of clients that implement timestamps in very different ways.
The most effective solution I have seen, is to simple provide a panel to allow your users to choose what time format they like. Some users even ****gasp**** like ISO formats. Then you do the time format conversion server side. If your application language does not have good locale to timezone formatting mapping, check your database. Many databases provide locale-based customized timezone formatting as well.
Because this anwser still popups in google I share that this is now possible to do by using a readonly datetime-local input (see below) and you can then style the input the way you want:
<input type="datetime-local" value="2018-06-12T19:30" readonly />
For more information see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

Categories

Resources