using moment js to pass in time zone and get hours offset? - javascript

I want to pass a three-digit time zone string like "GMT" or "EST" and get the offset like "-05:00" as a string from it.
Moment seems to handle it but I couldn't find a way...

This capability you are asking about has been deprecated. Tim Wood in this thread says:
The problem is that Date.prototype.toString returns such different results. That is the only place to get the timezone name (PST, CST, EST, etc). If this method is not returning any timezone information (as is the case with FF10 and IE9, there is no way to get it.
In that same thread there are mentions by some people about how they are able to get the abbreviated time zone and consequently pass it to moment but only in certain browsers.

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.

MomentJS .date() issue

Could anyone please explain me why moment("2013-04-22 00:00:00+07:00").date() returns 21?
For example moment("2013-04-22 00:00:00+02:00").date() returns 22.
I would be interested in getting the date without taking into account any timezone info in the string from which the moment object is built, i.e. always 22 in this particular example.
I think I figured it out: moment("iso8601_string") parses/converts that string into a local time. In my case, I'm in the UTC+2 timezone, so parsing strings containing "+02:00" (or "+01:00") and then calling .date() returns 22 because the time stored in the moment object matches my local time.
However, when parsing a string with e.g. "+07:00", the time stored in the moment object will be my local time, in which case the date will actually be different, a day before.
I think also my original requirement was convoluted and based on an incorrect assumption. My use-case was that I got the datetime from some UI widget always as date+time, but I needed only the date. Writing a unit test which parsed a string containing "+07:00" caused the date to be "incorrect". However this was an incorrect assumption, because (at least in my use-case) the datetime from the UI widget will always be in the local time so the code won't ever parse a string containing "+07:00".
I'm not sure that a use-case as I originally stated does exist in the real world:
you get a string containing a date in another timezone
you need to take the date out of it, but in the timezone of that date (why?)
I guess normally whenever getting a date from somewhere remote the convention is to always get UTC, that way the point of reference is clear and you can convert it further locally. So probably the case when you get a date in a random timezone and need the date from it, in that timezone, isn't common. Still, as an academic question, I don't know how I would be able to get the date out of it in that case :)

Moment js utc() time in london - BST

I'm using momentjs lib to updated text on some ajax action. What I need to do is to set a current date & time in london. I'm using moment.utc() function but because of the summer time I'm one hour out.
For example running this on 14:26
console.log( moment.utc().format('HH:mm:ss') );
I'm getting 13:26:53.
Any idea on how to fix this?
Can you use momentJS timezone?
moment().tz('Europe/London');
EDIT: In case you try to use this without seeing the link, it's a separate library you have to include.
If you want the local time instead of the UTC time, just use moment() instead of moment.utc(). You're specifically asking for UTC, so you shouldn't be surprised when you get UTC :)
From the documentation:
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() instead of moment().
This brings us to an interesting feature of Moment.js. UTC mode.
While in UTC mode, all display methods will display in UTC time instead of local time.
This is assuming you always want the user's local time. If you want a specific time zone (London) which may not be the user's time zone and isn't UTC, then you should use the library indicated by Takuya's answer. I would think carefully before doing so though - while it may be a sensible approach, you should at least validate that first. It's often reasonable to display a time for user U1 in the time zone of user U2 - but here you're using a fixed time zone. That's only appropriate if you know that U2 will always be in London. It would be really confusing if actually U2 is in some other zone - either the same as or different to U1.

getting time zone when entering state and country (time zone to use in ics file)

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?

Convert timestamp with specified offset for timezone with Date();

I've been digging through as many things as I can find, and I can't seem to find what it is I am looking for, so I am coming to the conclusion that I either don't know what I am looking for or its not possible. Either way..
What I am trying to achieve is taking a timestamp example: 1373439600000 and a given offset of -12 to 12 (is that correct, as far as range goes?) so I can then take that timestamp above subtract from it accordingly, and pass that new timestamp to the Date() function so I can then manipulate it for human readable display.
The offset is two part, It is user specified in one instance while in the other it is going to default to the local getTimezoneOffset() if not specified. So trying to figure out how to take that range and work with that. To do everything accordingly.
Ideas? Am I even approaching this in a correct manor?
The timestamps I am working with are already UTC, not sure of that makes a difference.
The JavaScript Date type has many problems, but one of its major quirks is that it only understands two time zones - UTC, or Local. It uses UTC internally and in certain properties and functions like .toUTCString(), but otherwise it uses the local time zone.
Many browsers will accept an offset when parsing a Date from a string, but that will just be used to set the UTC time. Anything on the way out will be converted back to the local time zone again.
Fortunately, there are some great libraries out there for working around these problems. Moment.js is perfectly suited for this. Here is an example of what you might be looking for:
moment(1373439600000).zone(8).format("YYYY-MM-DD HH:mm:ss Z")
// output: "2013-07-09 23:00:00 -08:00"
Of course, you can format as needed, or pass in a more complex zone offset like "+05:30". And if you need to use an actual IANA time zone, there is the moment-timezone companion project, which you could do something like this:
moment(1373439600000).tz('America/New_York').format("YYYY-MM-DD HH:mm:ss Z")
// output: "2013-07-10 03:00:00 -04:00"
Unfortunately the Date object does not provide may facilities for working with timezones. If you have the offset though, you should be able to compute the offset in milliseconds. Then you can add (subtract?) that value to your timestamp and use it to construct the appropriate Date.
Does that help?

Categories

Resources