Home > Enterprise >  Set a specific date and time in javascript independant of the browser timezone and time
Set a specific date and time in javascript independant of the browser timezone and time

Time:09-28

My Problem seems simple but I couldn't find a decent simple solution yet. Usecase: Anyone in the world should be able to access a website and with a button set a date to 3, 5 or 10 days in the future, 23:59:59 in GERMANY. This should be independant of the browser location or a wrong date / time setting on the client browser. I can get the server date / time via php inject which i can use as reference. So ideally i can just work with that but as soon as i do any operation with the date it is always handled in the timezone of the browser. So if i set the time to 23:59:59 then it is set according to browser timezone. Any idea how to just work with a timezone independant of the browser? Summertime should also be considered.

Basically i need a function like: SetDate(Today_In_Germany x days at 23:59:59)

Example code:

var t_date =  new Date(); 
t_date.setDate(t_date.getDate()   5)); //Add 5 days to current day
t_date.setHours(23,59,00,00); //Set it to 23:59

This works perfectly well within one timezone. But if you access the function from a different timezone it will set it to 23:59 of the timezone you are in, not the timezone of Germany which i want to set. Plus if your computer clock is wrong i get the wrong time.

CodePudding user response:

Date object doesn't have that feature. New temporal proposal does.

let dt = Temporal.ZonedDateTime.from({
  timeZone: 'Europe/Berlin',
  year: 2021,
  month: 9,
  day: 27,
  hour: 23,
  minute: 59,
  second: 59
})

Without Temporal, you need library like MomentJS.

CodePudding user response:

Until the Temporal implementation Barney mentioned is released i will use jabaas approach slightly modified. I inject the unix timestamp of Germany's today 23:59:59 via server side script. Then i can freely add 60x60x24 seconds for each day in the future and i will not get confused with Timezones. Not the solution i initally wanted but a solution which works for me.

  • Related