0

I need to convert German local time records, without zone info, i.e.,

var data = [
  "2017-12-02 20:27:02",
  "2017-12-02 20:50:00"
]

to UTC records, i.e., subtract the time zone offset and respect the daylight saving. I know that there are the getTimezoneOffset and toISOString functions, which would work if my system locale is set German. For instance I could convert the dates using

var d = new Date(data[0])
> Sat Dec 02 2017 20:27:02 GMT+0100 (CET)
d.toISOString()
> '2017-12-02T19:27:02.000Z'

However I need a safe solution that works on any server with any locale, e.g., in the cloud.

Juve
  • 10,584
  • 14
  • 63
  • 90
  • 3
    use moment and specify the locale? – yBrodsky Dec 22 '17 at 19:16
  • The time zone offset can be added in the string too. For example `new Date(data[0] + "z+1")` or `new Date(data[0] + " utc+1")` – Slai Dec 23 '17 at 00:26
  • 1
    @Slai just adding the offset is not safe, you also need to determine and add or subtract daylight saving offset, which is not easy to do as you need to reason about each specific calendar date. Using moment.js is the better solution. – Juve Dec 23 '17 at 17:27

2 Answers2

0

Thx to yBrodsky's comment I found a solution using moment-timezone:

moment = require("moment-timezone")
var d = moment.tz(data[0], "Europe/Berlin").toDate()    
d.toISOString()
> '2017-12-02T19:27:02.000Z'
Juve
  • 10,584
  • 14
  • 63
  • 90
0

You can use moment.js to make date calculations in JavaScript. To parse a date in a specific timezone, you also need moment.js timezone. You can then parse the date with your format in the tz() function. The date is then available as a moment object, with which you can use all moment.js features (e.g. time/date calculations, formatting, etc.). See the example below:

var dateString = '2017-12-02 20:27:02';
var dateFormat = 'YYYY-MM-DD HH:mm:ss';
var date = moment.tz(dateString, dateFormat, "Europe/Berlin");

console.log(date.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87