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.
Let's say, for example, that a store promotion starts at 9am for all stores worldwide. This means that it starts at 9am CST for stores in Chicago, 9am PST for stores in Seattle, and 9am GMT for stores in the UK.
In our promotions table on Postgres, we would set the start time for this promotion as 09:00:00.
Each store has a computer with a web browser that looks up available promotions. It needs to pass its local time to the server so that the server can return all promotions for that local time. Thus we need to find a way to capture the local time in JavaScript, encode it, send it to a Java backend, reconstruct it, and then compare that with the start time in the promotions table.
The local time, of course, depends on the time zone. If it's 9am in Chicago then a store in Chicago should tell the server that it's 9am. It's futile to send the UTC time without some indication of the time zone.
Question: What's a good way to capture the local time (based on time zone) in JavaScript, encode that, send it to a Java backend, reconstruct it as a Java Date, and then compare that Java Date with the 9am promotion start time in the Postgres database?
My (unsatisfactory) approach: The best I can think of is to send the UTC time in milliseconds using JavaScript's Date.getTime method, along with the time zone offset, which can be calculated in minutes using JavaScript's Date.getTimezoneOffset method and converted to milliseconds. Subtracting the time zone offset from the UTC time in milliseconds, we can then create a Java Date object from the resulting difference. If it's 9am in Chicago, then, hopefully, the Java Date will store 9am. What's a little odd about this approach, however, is that the Java Date will actually be storing 9am UTC, even though it's representing 9am CST. This is just one of the reasons why I am not satisfied with this approach. Can you think of something better?
Postgres
In Postgres, when you mean 9 AM everywhere, or 9 AM anywhere, on a certain date, use the column data type TIMESTAMP WITHOUT TIME ZONE. Any time zone or offset-from-UTC included with an input is ignored, with the date and time-of-day taken as-is (no adjustment) and stored. This data type purposely lacks any concept of time zone or offset-from-UTC.
For time-of-day without a date, use TIME WITHOUT TIME ZONE data type. Postgres also offers a TIME WITH TIME ZONE only because it is required by the SQL spec; this WITH type is nonsensical and should never be used.
Postgres is an excellent choice for such a project, as it offers excellent date-time support in both its data types and in its functions. Databases vary widely in their date-time features.
Java
On the Java backend, use only the modern java.time classes. These years ago supplanted the terrible old date-time classes bundled with the earliest versions of Java.
If not yet using Java 8 or later, find nearly all the same functionality in a back-port to Java 6 & 7 in the ThreeTen-Backport project. Well worth the minor effort of adding this library to your project. From the same fine folks who brought you the java.time classes and the Joda-Time project, all led by the same man Stephen Colebourne.
LocalDateTime
In java.time, use LocalDateTime class for when you mean 9 AM anywhere/everywhere on a certain date. Like TIMESTAMP WITHOUT TIME ZONE in Postgres, this class purposely lacks any concept of zone or offset.
LocalDateTime ldt = LocalDateTime.of( 2018 , 1 , 23 , 15 , 0 , 0 , 0 ) ; // 3 PM on 23rd of January this year.
LocalTime
If you mean the time-of-day only, without a date, use the class LocalTime.
LocalTime lt = LocalTime.of( 15 , 0 ) ; // 3 PM.
JDBC
As of JDBC 4.2 and later you can exchange java.time objects with the database via getObject and setObject methods.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
If your JDBC drivers are not yet updated to 4.2, then fall back to the awful old legacy classes, but convert immediately to the java.time classes.
Given that the legacy classes lack a class for a date plus time-of-day without time zone, we have to fake it. Use java.sql.Timestamp which represents a moment in UTC with a resolution of nanoseconds, and just ignore the fact that it is in UTC.
java.sql.Timestamp ts = myResultSet.getTimestamp( … ) ;
For Java 8 and later, convert using new methods added to the old classes. Convert first to java.time.Instant, which also represents a moment in UTC with a resolution of nanoseconds. Then convert to a LocalDateTime by effectively removing the concept of UTC.
Instant instant = ts.toInstant() ; // Convert from legacy class to modern one.
LocalDateTime ldt = LocalDateTime.ofInstant( instant , ZoneOffset.UTC ) ; // Remove the concept of UTC (or any other offset or zone) from our data.
For Java 6 & 7 using the ThreeTen-Backport library, use the conversion methods in their utility DateTimeUtils class.
org.threeten.bp.Instant instant = org.threeten.bp.DateTimeUtils.toInstant( ts ) ; // Convert from legacy class to modern.
org.threeten.bp.LocalDateTime ldt = LocalDateTime.ofInstant( instant , ZoneOffset.UTC ) ; // Remove the concept of UTC (or any other offset or zone) from our data.
ZonedDateTime
The Local… classes by definition have no real meaning until you place them in the context of a time zone. A LocalDateTime is not a moment, does not represent a point on the timeline.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as PST or BST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
LocalDateTime ldt =
LocalDateTime.of(
LocalDate.of( 2018 , Month.January , 23 ) ,
LocalTime.of( 9 , 0 )
)
;
ZoneId zLosAngeles = ZoneId.of( "America/Los_Angeles" ) ; // Seattle time zone.
ZonedDateTime zdtSeattle = ldt.atZone( zLosAngeles ) ;
ZoneId zChicago = ZoneId.of( "America/Chicago" ) ;
ZonedDateTime zdtChicago = ldt.atZone( zChicago ) ;
ZoneId zLondon = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdtLondon = ldt.atZone( zLondon ) ;
There we have three ZonedDateTime objects: zdtSeattle, zdtChicago, and zdtLondon. These are all 9 AM on the 23rd of January earlier this year. Understand that these are three very different moments, each being several hours earlier as you go eastward. They all have the same wall-clock time (9 AM on 23rd) but are three different points on the timeline.
JavaScript
While I do not know JavaScript well enough to say for certain, I doubt you have any library there as rich for date-time handling. The java.time framework is industry-leading.
As for web client user-interface development, I use Vaadin, so it is a non-issue: pure Java on back-end auto-generates the HTML/CSS/DOM/JavaScript needed by the web browser.
find a way to capture the local time in JavaScript
As for detecting the current default time zone in the client machine, I’m no expert, but as I recall the browsers do not return a named time zone, only an offset-from-UTC. See the Answer by Matt Johnson for a possible solution. In any app (desktop or web), ultimately, if the correct time zone is vital, then you must ask or confirm the desired/expected time zone with the user. And it may be wise to always indicate somewhere on your user interface what time zone is being used by your app.
If you need to exchange date-time values between your Java backend and JavaScript code in the front-end, you have two choices primarily:
ISO 8601
Count-from-epoch
ISO 8601
The ISO 8601 standard defines a variety of textual formats for exchanging date-time values. These are wisely designed to avoid ambiguity. They are easy to parse by machine, and easy to read by humans across cultures.
The java.time classes use these formats by default when generating/parsing strings.
Count-from-Epoch
I do not recommend this approach, as it is confusing and error-prone, subject to ambiguity and incorrect assumptions between the people and libraries who are sending or receiving.
An epoch reference date is a point in time used as baseline. Then some count forward or backward is made of some granularity.
One big problem is that there are dozens of epoch references used by various systems. The java.time classes by default use the Unix time epoch of first moment of 1970 in UTC, 1970-01-01T00:00Z.
Another problem is that there are many granularities such as whole seconds, milliseconds, microseconds, and nanoseconds. Programmers must document/communicate clearly what granularity is in play.
If you were to be sending your three opening moments for your three stores to JavaScript as a count-from-epoch, you would be sending three different numbers.
long millisecondsSeattle = zdtSeattle.toInstant().toEpochMilli() ;
long millisecondsChicago = zdtChicago.toInstant().toEpochMilli() ;
long millisecondsLondon = zdtLondon.toInstant().toEpochMilli() ;
Results in three different numbers for three different moments.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You do not need to capture the user's local time, but merely their IANA time zone identifier, such as "America/Los_Angeles". This can then be used in your Java back-end code in APIs that accept a time zone.
In most modern browsers, you can capture the the time zone id like this:
Intl.DateTimeFormat().resolvedOptions().timeZone
If you require supporting older browsers, there are several libraries that will use this Intl API when available, but will fall back to an educated guess when not. More on this here.
Getting time zone when giving state and country in text box
is there any way to get the time zone of that place with this two values?
the input will be like
var state = 'New York' ;
var country = 'United States';
result should be
America/New_York
OR
get local time zone of the current browser?
I need this time zone to use in ics file.
This is impossible, for the simple reason that quite a few states span more than one timezone. See Wikipedia's list. Outside the US it can get even more complicated; I believe there are some cities that span multiple timezones.
You could cobble together guesses per state (e.g. by using that list), but if this is for figuring out the user's timezone, you'll probably have better luck just comparing the client clock with the server's UTC time and estimating based on country.
edit: Note that there's no way to ask the browser for the current timezone, either, and you can't guess reliably based on the current time, because there are many timezones where it's the same time right now but where DST is different. Your best bet is to find all the possible current timezones, estimate based on the user's location (which you also have to guess!), and just ask as a last resort.
No, there is no pre-defined methods exists.
For this you need some external web services. If you're interested you can create your own API using the information provided here in wikipedia
Updates: Based on your comments "get local time zone of the current browser
var date = new Date();
returns 12:38:05 GMT+0530 (India Standard Time)
To pick the time within the bracket use
date.toTimeString().match(/\(([^)]+)\)/)[1];
returns India Standard Time
Check this JSFiddle
But this is not you expected, however you should try Auto detect a time zone with JavaScript and for updated version try this jsTimezoneDetect
GeoNames provides a data dump that you can use:
http://download.geonames.org/export/dump/
This is per skylarsutton's response in the following previous post with a similar question (but not specific to js or query)...
I need a mapping list of cities to timezones- best way to get it?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript/PHP and timezones
It is possible to get the Olson timezone id from javascript on the client's machine e.g. (America/New York). I know that PHP can do this via the timezone object, something like this. $timezone->getLocation(); Does similar functionality exist for JS?
I know that you can grab the timezone offset of the client as followed:
var curdate = new Date();
var offset = curdate.getTimeZoneOffset();
But I need more granular information provided by the Olson Id. Thank you for your help.
You can't directly access timezone in JavaScript. You can, however, measure offsets reported at several different specific dates to deduce what exactly time zone is in use by comparing regular and daylight savings times to database of zones. There's a jsTimezoneDetect library that can do most of this work for you.
This question already has answers here:
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 6 years ago.
I have a web application that has a dynamic javascript calendar, which allows users to set events for a given data and time. I need to push notifications to the users, so I need to convert the date time and timezone they entered, into Eastern Standard Time, so that my notifications are sent out at the correct time.
I would like to do this in javascript, so that when the data time value gets to the php, it's in the right format, before being added to the database.
So to summarize, I need to convert a javascript datatime and timezone, which I get by capturing the users datatime, as a full UTC date, to my servers timezone, which is EST - New York.
Any help or direction on this matter, would be greatly appreciated.
Thanks :)
Pl check this script
function convertToServerTimeZone(){
//EST
offset = -5.0
clientDate = new Date();
utc = clientDate.getTime() + (clientDate.getTimezoneOffset() * 60000);
serverDate = new Date(utc + (3600000*offset));
alert (serverDate.toLocaleString());
}
I would draw the EST timezone offset into the page while you're rendering it (via PHP) and then grab the UTC time on the client and offset it by the amount you've drawn in. Otherwise, if your server ever moves timezones your page will suddenly be reporting the wrong time.
I just did this recently though, and found that the simplest way to handle this is to actually use mySQL (I'm assuming that's your DB), and just let IT convert the timezone for you while you're entering the date stamp. Unless you're worried this is too tasking and you're trying to absolutely reduce the work your db is doing, I'd go that route, rather than muck about trying to do manual TZ conversions in JS.