Juve Juve - 2 months ago 46
Node.js Question

Convert historical german local time record to UTC in JavaScript

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
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)
> '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.

Answer Source

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");

<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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download