Buster3650
Buster3650

Reputation: 478

How to convert datetime to UTC+1 in JavaScript

We have created a function in node-red, where we cleaning a datetime received from the metadata of a sensor. Unfortunately, the timezone fetched is one hour behind, and therefore a "wrong datetime" is sent. We need to convert this datetime to UTC+1 ('Europe/Berlin'). The function is in JavaScript, and in my knowledge we can't use third party libraries like moment etc.

Hopefully, someone here can help us. Thanks in advance!

This is what we have done so far:

var time = msg.metadata.time;

var datetime = new Date().toLocaleString();
var timedate = new Date(time);

var y = timedate.getFullYear().toString();
var m = (timedate.getMonth() + 1).toString();
var d = timedate.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);

timedate.setHours(timedate.getHours() + 1)

var h = timedate.getHours().toString();
var min = timedate.getMinutes().toString();
var s = timedate.getSeconds().toString();
(h.length == 1) && (h = '0' + h);
(min.length == 1) && (min = '0' + min);
(s.length == 1) && (s = '0' + s);

var date = y+'-'+m+'-'+d
var time = h + ":" + min + ":" + s;

var timeDate = date+' '+time;

Upvotes: 0

Views: 731

Answers (2)

Terry Lennox
Terry Lennox

Reputation: 30705

I would consider using Date.toLocaleString() for date/time conversion.

Now Moment.js will be better if you can use it, but you can convert times like below.

Remember you must consider DST changes and these are hard to account for using your own code (the exact dates of DST switchover change from year to year).

For example, Berlin uses CET (UTC+1) from late October to late March and CEST (UTC+2) from late March to late October.

Why am I using a locale of "sv", this is because it will essentially give us an ISO 8601 timestamp. Of course for converting to text you can use any locale.

I've added a getUTCOffsetMinutes function that will return the UTC offset in minutes for a given UTC time and timezone.

A list of IANA timezones is here: timezone list

const time = 1559347200000; // 2019-06-01T00:00:00Z

console.log("UTC time 1:", new Date(time).toISOString());
console.log("Berlin time 1 (ISO):", new Date(time).toLocaleString("sv", { timeZone: "Europe/Berlin"}));
console.log("Berlin time 1 (de):", new Date(time).toLocaleString("de", { timeZone: "Europe/Berlin"}));

const time2 = 1575158400000; // 2019-12-01T00:00:00Z
console.log("UTC time 2:", new Date(time2).toISOString());
console.log("Berlin time 2 (ISO):", new Date(time2).toLocaleString("sv", { timeZone: "Europe/Berlin"}));
console.log("Berlin time 2 (de):", new Date(time2).toLocaleString("de", { timeZone: "Europe/Berlin"}));


// You can also get the UTC offset using a simple enough function: 
// Again, this will take into account DST 

function getUTCOffsetMinutes(unixDate, tz) {
  const localTimeISO = new Date(unixDate).toLocaleString("sv", {timeZone: tz}).replace(" ", "T") + "Z";
  return (new Date(localTimeISO).getTime() - unixDate) / 60000; // Milliseconds to minutes.
}

console.log("UTC offset minutes (June/Berlin):", getUTCOffsetMinutes(time, "Europe/Berlin"));
console.log("UTC offset minutes (June/LA):", getUTCOffsetMinutes(time, "America/Los_Angeles"));
console.log("UTC offset minutes (June/Sydney):",getUTCOffsetMinutes(time, "Australia/Sydney"));

console.log("UTC offset minutes (December/Berlin):", getUTCOffsetMinutes(time2, "Europe/Berlin"));
console.log("UTC offset minutes (December/LA):", getUTCOffsetMinutes(time2, "America/Los_Angeles"));
console.log("UTC offset minutes (December/Sydney):", getUTCOffsetMinutes(time2, "Australia/Sydney"));

Upvotes: 3

LeandroP
LeandroP

Reputation: 377

I use this function I made, i think it may help you:

function formatDateToOffset(date, timeOffset){
    var dateInfo, timeInfo;

    // change date's hours based on offset
    date.setHours(date.getHours() + (timeOffset || 0))
    // place it the way you want to format
    dateInfo = [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]
    timeInfo = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()];

    // return the string formatted date
    return dateInfo.join("-") + " " + timeInfo.join(":");
}
console.log(formatDateToOffset(new Date(), 1))

Upvotes: -1

Related Questions