0

I have a scheduled cloud function which runs in Europe/Berlin timezone. Long story short, I need to get day number in a year.

I've used this code for that:

https://stackoverflow.com/a/8619946/4195212

At time when I'm writing this if I run a code in the snippet inside the answer posted above it will show me 221 (which is correct). But in my cloud function it is 220.

I thought I need to set a timezone correctly, which I did. But still it shows the wrong day number.

What is wrong here?

exports.scheduledFunction2 = functions.region('europe-west3').pubsub.schedule('every minute').timeZone("Europe/Berlin").onRun((context) => {
    var now = new Date();
    var start = new Date(now.getFullYear(), 0, 0);
    var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
    var oneDay = 1000 * 60 * 60 * 24;
    var day = Math.floor(diff / oneDay);
    console.log('Day of year: ' + day); // prints 220

})
JM Gelilio
  • 3,482
  • 1
  • 11
  • 23
harunB10
  • 4,823
  • 15
  • 63
  • 107

1 Answers1

1

I have a scheduled cloud function which runs in Europe/Berlin timezone.

Using pubsub.schedule().timeZone() to change the timezone of Cloud Function will not work. It sets only the timezone for the scheduler. It means it doesn't change the timezone inside the function's execution. That's the reason you are still getting the default time of Cloud Function.

Therefore, you also need to configure the timezone for Cloud Function and there are many ways to do it. For example, you can use momentjs timezone plugin:

momentjs:

var moment = require("moment-timezone");
var now = moment().tz("Europe/Berlin").format();
console.log(now); // print 2021-08-11T07:20:54+02:00
JM Gelilio
  • 3,482
  • 1
  • 11
  • 23