【问题标题】:Nodejs create a date with timzoneNodejs创建带有时区的日期
【发布时间】:2020-09-07 16:04:28
【问题描述】:

我可能比我需要的更难。

我在服务器上使用 nodejs。前端将偏移量发给我。

我需要昨天(或今天、上周...)的 UTC 等值,例如,基于偏移量。

目前我有:

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
  };
}

但这一切都基于服务器时区。我需要它基于从前端发送的偏移量。

所以今天需要使用 UTC。因此,如果偏移量是 420 (-7),那么即使服务器在危塔马拉,昨天也需要从 '2020-05-19 07:00:00.000' 到 '2020-05-20 07:00:00.000'。

我的想法是在 UTC 中获取今天的日期(而不是时间),然后添加(或减去)偏移量。然后使用该日期添加Days。

我宁愿不使用额外的库。

吉娜

【问题讨论】:

  • 您只想在 GMT+0000 与 date 约会吗?
  • @DupinderSingh 正确
  • 我更新了答案请看一下

标签: javascript node.js


【解决方案1】:

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>

并通过时差或我们可以说的偏移来管理使用以下脚本

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);

【讨论】:

  • 我期待:2020-05-21T00:00:00.000Z
  • 你现在能看到这个吗,我想这正在解决你的问题
  • 好吧。解释答案
【解决方案2】:

我在这里找到了答案:stackoverflow answer

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

这允许我创建“昨天的”日期范围:

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
   };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多