Desperate for help here, sorry this pure javascript (with moment-timezone library), not directly tied to node-red, but need this to work in node red regardless.
I got 2 input strings:
- date (string on format "yyyy-MM-dd hh:mm")
- tz (timezone string, for example "Europe/Oslo")
Seconds doesn't matter here. I need this converted to unix time epoc number. It looked straight forwad, but no matter what I do with tz, it produce same output!
import moment from "moment-timezone";
const localTime = "2025-01-15 00:00";
const timezone1 = "Europe/Oslo";
const timezone2 = "Australia/Melbourne";
function localTimeToUnixTimestamp(localDateTime, timezone) {
const m = moment.tz(localDateTime, 'YYYY-MM-DD HH:mm', timezone);
return m.unix();
}
// Example usage:
const a = localTimeToUnixTimestamp(localTime, timezone1); // 1736937000
const b = localTimeToUnixTimestamp(localTime, timezone2); // 1736937000
console.log(a == b); // true !?!
If I'm lucky someone has some experience with this and can help me trapped in timezone nigthmare haha.
I am way out of my depth here.
So the code you posted:
const a = localTimeToUnixTimestamp(localTime, timezone1); // 1736937000
const b = localTimeToUnixTimestamp(localTime, timezone2); // 1736937000
console.log(a == b); // true !?!
I am confused with the last line.
And most of the code. But from an outside perspective:
You define two zones so when you send the time to the code it translates it from the local time to Unix time.
So what is this last line: console.log(a == b);
(I posted this as I saw someone else replying and hoped they may help you better than I can.)
You call your routine and get back a return (which from the routine's point of view is m
.
But is either a
or b
in the last lines.
So I am at a huge loss why you are saying (a == b)
1 Like
Sorry it was something else completely. The reason I had a == b was I tried to set different timezones, which should give different result. But they were always identical (indicating timezone was not effectively applied).
I was playing around with code in vscode using a repl js extension to get live feedback. Turns out timezones wasn't loaded correctly there Took a few hours before I figured out haha.
So when running the js file from command line, or in node red, it should take timezone into account.
Glad I helped - or I hope I did.
All the best.
Yes thanks a lot, always helpful. Strange situation when playing around in vs code. When running from command line (node .\src\test.js
), it works with normal import moment from "moment-timezone";
. But when running JS REPL plugin in vscode, that won't load the timezone data properly, so it just ignores it silently. So you still get timestamps or whatever without taking timezone into account... Turns out a different import worked for JS REPL (but breaks command line haha): import moment from "moment-timezone/builds/moment-timezone-with-data";