Timezone javascript cloud

Hello,

I am on the cloud version and trying to get the Date working properly, i need to know how much time between two dates is past. I am doing this in a function but the timezone for Javascript is not the same as i did set in the settings.

This is also about this issues but this could be a own server and can be fixed serverside.
N8n cloud, MYSQL connection times out - Questions - n8n

Any ideas?

Hi @Gijs_Epping :wave:

Date functions in JavaScript can be a bit tricky unfortunately.

My usual approach would be to use the ISO 8601 format wherever possible, to avoid time zone issues. For example, in a function node I could calculate the difference between two dates (and return them) like so:

const firstDate = new Date('2021-10-11T14:20:00Z');
const secondDate = new Date('2021-10-11T14:20:30Z');
const differenceInMilliseconds = secondDate - firstDate;

return [{
  json: {
    differenceInMilliseconds: differenceInMilliseconds
  }
}]

This should work regardless of the server time zone.

Would you be able to share how exactly you calculate your timespan between the two Dates and what goes wrong for you?

1 Like

Thanks for the help @MutedJam

I got it working finally, the time from n8n was alway 2 hours behind my time. So i just needed to add two hours.

  • ShopWare: 2021-10-11T19:28:45.000Z
  • My Time: 2021-10-11T22:04:42.096Z
  • n8n: 2021-10-11T20:04:42.096Z

So i needed to add some hours to compare, final script is this.

var d1 = new Date(items[0].json.orderTime), // order Date
    d2 = new Date(); // now date
    d2.setHours( d2.getHours() + 2 ); // add two hours

var diff = d2 - d1;

var resultDiff = Math.floor(diff / 60e3);

items[0].json.diff = resultDiff;

return items;

Thanks again for your help!

1 Like

Did you try the Date & Time node?