1

I am probably making this harder than I need to.

I am using nodejs on the server. The front-end send me the offset.

I need the UTC equivalent of yesterday (or today, last week...), for example, based on offset.

Currently I have:

getYesterday(): DateRange {
  const today = new Date();
  const fromDate = format(addDays(today, -1), DATE_SERVER_FORMAT);
  const toDate = format(today, DATE_SERVER_FORMAT);

  return {
    fromDate,
    toDate
  };
}

But this is all based on the server timezone. I need it based on the offset sent from the frontend.

So today needs to be in UTC. So if the offset is 420 (-7) then Yesterday needs to be '2020-05-19 07:00:00.000' to '2020-05-20 07:00:00.000' even if the server is in Guatamala.

My thoughts are to get today's date (not time) in UTC then add (or subtract) the offset. Then use that date to addDays to.

I'd rather not use an additional library.

Gina

Gina Marano
  • 1,773
  • 4
  • 22
  • 42

2 Answers2

1

I found the answer here: stackoverflow answer

var d = new Date();
d.setUTCHours(0,0,0,0);
console.log(d.toISOString());

Which allows me to create "yesterday's" date range:

getYesterday(offset :number): DateRange {
   var today = new Date();
   today.setUTCHours(0,0,0,0);
   today = addMinutes(today, offset);

   const fromDate = addDays(today, -1).toISOString();
   const toDate = today.toISOString();

   return {
     fromDate,
     toDate
   };
}
Gina Marano
  • 1,773
  • 4
  • 22
  • 42
0

var date1 =  new Date();
var date2 =  new Date();

console.log(date2.toUTCString());
console.log(date1.getUTCDate());
<h1>Date UTC +_ 0000</h1>

<pre>
  You can see the date of output
  console.log(date1.getUTCDate());
  and 
  console.log(date2.toUTCString());
  is Same
  
  So the simple way to get UTC Date and Time is in built in Date API
  
</pre>

And to Manage with time difference or what we can say offset Use following script

var targetTime = new Date();

var timeZoneFromClient = -7.00; 

var tzDifference = timeZoneFromClient * 60 + targetTime.getTimezoneOffset();

//convert the offset to milliseconds
//add to targetTime
//make a new Date
var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);

console.log(offsetTime);
Dupinder Singh
  • 7,175
  • 6
  • 37
  • 61