2

I have a Pacific time, e.g. 2016-09-09 01:57:42. To convert it to UTC time I used

d = new Date('2016-09-09T01:57:42-0700')

But the problem is for PDT I have to use -0800. So how can the Pacific time (may be -0700 or -0800) be smartly converted to UTC time?

pynexj
  • 19,215
  • 5
  • 38
  • 56

2 Answers2

0

Date/time is a nightmare. Use an existing library that does this for you. Moment.js Timezone is a popular choice.

var d = moment('2016-09-09T01:57:42-0700').tz('UTC');
Brad
  • 159,648
  • 54
  • 349
  • 530
  • 1
    One of the few places where "use a library, don't do this yourself" is the correct answer. @whjm - The rules are complex and have changed over time. Don't roll your own. – T.J. Crowder Sep 12 '16 at 05:15
  • See this [stack post](https://stackoverflow.com/questions/47046067/typeerror-moment-tz-is-not-a-function) for how to include moment in react. – Richard Tyler Miles Jun 18 '22 at 15:46
-1

If you want to convert your PST timezone to UTC than you can use following code :

$date = new DateTime('2016-09-09 01:57:42');
$date->setTimezone(new DateTimeZone('UTC'));
echo "The UTC is " . $date->format('Y-m-d H:i:s') . "<br>";

You can see list of supported timezones here by PHP :

http://php.net/manual/en/timezones.php

Let me know if it is work or not ?

Hardik Patel
  • 706
  • 5
  • 14
  • For eg. `2016-09-09 01:57:42` If this is pacific time than it will work. – Hardik Patel Sep 12 '16 at 06:35
  • How can it work since you did not provide it with any information about the timezone? – pynexj Sep 12 '16 at 07:07
  • It will consider as you are passing UTC time. If you are not having UTC time than you should first convert it. – Hardik Patel Sep 12 '16 at 07:25
  • But it does not know what timezone the time `2016-09-09 01:57:42` is in. That's to say how do you tell it the time is *Pacific time*? – pynexj Sep 12 '16 at 07:26
  • If you are using JavaScript than you should visit this link : http://stackoverflow.com/questions/6525538/convert-utc-date-time-to-local-date-time-using-javascript – Hardik Patel Sep 12 '16 at 07:32