0

I have a date I want to convert based on their timezone.

For example, I want to set it in EST time (America/New_York)

2019-04-24 12:00:00

and if the user comes across the site from America/Los_Angeles, it will appear:

2019-04-24 09:00:00

I need to be able to return the hour, so in that example: 9.

I tried using https://github.com/iansinnott/jstz to determine their timezone and https://moment.github.io/luxon in hopes of handling the conversion w/o any luck.

I was testing by changing the timezone on my computer w/o any luck.

Brad
  • 12,054
  • 44
  • 118
  • 187
  • Won't the JavaScript Date object does the timezone conversion based on the client's timezone..? – wentjun Apr 24 '19 at 19:20
  • `new Date().getHours()` already does that. – str Apr 24 '19 at 19:24
  • 1
    Is the first part of your question asking how to create a `Date` instance from a datetime string that represents a specific time zone (i.e. "America/New_York")? Regarding the second part of your question, many JavaScript `Date` methods like `getHours()` automatically return values in local time, are you looking for some other behavior? – benvc Apr 24 '19 at 19:28
  • why arn't you using NTP api. Network Time protocol, This will always return time, from the Network, which is User using in his or her devide, like from Internet service provider or Sim card in the devide !!!! Have a look; http://www.ntpjs.org/ – Dupinder Singh Apr 24 '19 at 19:41
  • Use NTP because of following reason: User may fool the application by changing Device date and time, But NTP will provide TIme date from server for that particular location of user :) cheers – Dupinder Singh Apr 24 '19 at 19:47
  • @DupinderSingh - Nothing in this question is about retrieving the current time. Your comments are off-topic. – Matt Johnson-Pint Apr 24 '19 at 22:27

5 Answers5

1

It sounds like you're asking to convert from a specific time zone to the user's local time zone (whatever it may be). You do not need time zone detection for that, but at present you do need a library. (Answers that suggest using toLocaleString with a time zone parameter are incorrect, as that function converts to a specific time zone, but cannot go the other direction.)

Since you mentioned Luxon, I'll provide a Luxon specific answer:

luxon.DateTime.fromFormat('2019-04-24 12:00:00',       // the input string
                          'yyyy-MM-dd HH:mm:ss',       // the format of the input string
                          { zone: 'America/New_York'}) // the time zone of the input
              .toLocal()                               // convert to the user's local time
              .toFormat('yyyy-MM-dd HH:mm:ss')         // return a string in the same format

//=>  "2019-04-24 09:00:00"

This capability is also provided by other libraries, such as date-fns-timezone, js-Joda, or Moment-Timezone, but it is not yet something built in to JavaScript.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
0

You could keep a list of timzeone identifiers and a list of their corresponding +/- number of hours with respect to your local time (which is returned by your time function).

Once you have a user's time zone, and you have extracted the current hour from the local timestamp simply look up the timezone in your list and use it's index to access the second list to find how many hours to add or subtract from the users time.

Tom
  • 1
  • 2
  • Sorry, but this approach will not work. Read the section "Time Zone != Offset" in [the timezone tag wiki](https://stackoverflow.com/tags/timezone/info). – Matt Johnson-Pint Apr 24 '19 at 22:10
0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));

// toLocaleString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleString());
// → "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles

Or you can use getYear, getMonth, getDate, getHours, getMinutes, getSeconds to format your own representation of the date. These methods all return values according to the user's local timezone.

mlrawlings
  • 711
  • 4
  • 9
0

Converting date based on the time can be done like this. reference convert date to another time zone example snippet is under.

var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
usaTime = new Date(usaTime);
console.log('USA time: '+usaTime.toLocaleString())


var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/Los_Angeles"});
usaTime = new Date(usaTime);
console.log('USA time: '+usaTime.toLocaleString())
  • Nooo.... you cannot just take the output of `toLocaleString` and pass it back to the `Date` constructor. That is asking for trouble... The `Date` string parser is not required to accept locale specific formats, and the input would be treated as if it were in the *local* time zone. Don't do this. – Matt Johnson-Pint Apr 24 '19 at 22:08
  • This is a better solution. The requirement has been accomplished even without using a library. – Sachintha Nayanajith Apr 25 '19 at 03:57
  • @MattJohnson Tell me why this is asking for trouble and tell me why Date string parser is not required to accept local specific formats ? – Sachintha Nayanajith Apr 25 '19 at 04:01
  • 2
    @SachinthaNayanajith as far as i see at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters when you construct a Date from a string the string has to be an IETF-compliant RFC 2822 timestamp or a version of ISO8601. From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString it doesn't seem that the format of toLocaleString() is bound to the same restrictions - it might be that this works by accident? – Sandman Apr 25 '19 at 15:20
  • 1
    Correct. The notes on the supplied link explain why. Anything beyond the spec is implementation dependent, and can vary significantly between implementations. Also, there's just no point to the second and third lines in the above code. The first line is fine, and already has the converted output. However, it doesn't answer the question that was asked, as this is converting ***from*** local time to a given time zone, where the OP asked how to convert in the opposite direction. – Matt Johnson-Pint Apr 25 '19 at 15:51
0

I think the question may need more clarification - my first impression was you refer to a date-time that you already have and serve from the server. Doesn't this problem boil down to the Date object being "user-timezone-aware"? or not? But it is (some methods are, to be exact)

Your date/time is 2019-04-24 12:00:00 EDT (i assume P.M.) This means the Unix timestamp of this in milliseconds is 1556121600000 (i assume daylight is on for April so not pure EST but EDT and an offset of UTC-4:00)

When you call

console.log(new Date(1556121600000).getHours())

doesn't this return 9 as you suggest, for Javascript executed on a browser from America/Los_Angeles with PDT timezone?

As suggested at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours :

The getHours() method returns the hour for the specified date, according to local time.

Sandman
  • 2,577
  • 2
  • 21
  • 32
  • While correct unto itself, this isn't what was asked. The OP didn't provide a Unix timestamp, or any input containing the offset from UTC. They asked for converting from a specific time zone to the user's local time. – Matt Johnson-Pint Apr 25 '19 at 15:56
  • Also the `Date` object is not time zone aware, but rather it has some functions (for both input and output) that make use of the local time zone. In your example, the only thing kept internally by the `Date` object is `1556121600000`. It's the `getHours` call that applies the local time zone before delivering a result. – Matt Johnson-Pint Apr 25 '19 at 15:56
  • Updated the answer to reflect that some methods, rather, are "timezone aware". I used Unix timestamp and UTC offset as a reference to properly place my example in time, to support the idea that there is a moment of 1556121600000 across the globe and that only its representation differs - it might help sometimes to get "out of a timezoned mindset"; and this is where the "input" comes in: if the user selects the input date/time then your answer is the one :) But if the programmer decides on it beforehand (and serves it from a server or hardcodes it) as i understood, this is what i answered :) – Sandman Apr 25 '19 at 16:09