2

what is the best way of getting current time in selected timezone as Date Object. I am using Following code to get current time at selected timezone in react native.

Eg. new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })

The output of this code is a string but I need it in Date Object. Every time I convert back to New Date() , it takes default timezone but I need custom timeZone. I also tried using moment library and momentTimeZone bu could not get correct output. Anyone can help me with this

Payalv
  • 91
  • 1
  • 7

2 Answers2

0

Date also takes a dateString as an argument and most of the string formats should work (that Date.parse() supports) :

> now = new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })
'12/26/2018, 3:51:28 PM'
> now_obj = new Date(now)
2018-12-26T14:51:28.000Z
Sharu
  • 77
  • 3
  • Thanks for the reply. My problem is I need to convert the string object obtained from new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' }) back to Date Object without changing timeZone of date Object. DatepickerIOS in React native component only takes Date Object as input. So, I need to convert the string to Date object. Every time I convert it back to Date , it takes default timezone , I need to keep timeZone unchanged. – Payalv Dec 26 '18 at 09:42
  • Sorry for a late reply. I see now that I misinterpreted your use case. – Sharu Jan 19 '19 at 11:17
0

It seems you can not do that unless you change your OS timezone to you want. You can define function instead of Date object as below:

function getCustomDate(zone) {
    return new Date().toLocaleString('en-US', { timeZone: zone })
}
anson
  • 67
  • 1
  • 6