代码之家  ›  专栏  ›  技术社区  ›  Ole

在Javascript中创建与时区无关的日期?

  •  0
  • Ole  · 技术社区  · 3 年前

    这个问题与 this question

    new Date("2000-01-01")
    

    根据我们所处的时区,我们可能会得到不同的年份和日期。

    我需要能够用Javascript构建日期,始终具有正确的 year , day month 2000-01-01 ,根据其中一个问题的答案,如果我们使用反斜杠,则如下所示:

    const d = new Date("2000/01/01")
    

    那么我们总是会得到正确的答案 , 当使用如下相应的日期API方法时:

    d2.getDate();
    d2.getDay();
    d2.getMonth();
    d2.getFullYear();
    
    

    最终我需要能够创造 Date 示例如下:

    const d3 = new Date('2010/01/01');
    d3.setHours(0, 0, 0, 0);
    

    , 应为字符串中指定的数字。

    思想?

    https://stackblitz.com/edit/typescript-eztrai

    const date = new Date('2000/01/01');
    console.log(`The day is ${date.getDate()}`);
    const date1 = new Date('2000-01-01');
    console.log(`The day is ${date1.getDate()}`);
    

    它记录了以下内容:

    The day is 1
    The day is 31
    

    因此,使用反斜杠似乎应该有效。。。

    或者使用年、月(基于0的索引)和日构造函数值,如下所示:

    const date3 = new Date(2000, 0, 1);
    date3.setHours(0, 0, 0, 0);
    console.log(`The day is ${date3.getDate()}`);
    console.log(`The date string is ${date3.toDateString()}`);
    console.log(`The ISO string is ${date3.toISOString()}`);
    console.log(`Get month ${date3.getMonth()} `);
    console.log(`Get year ${date3.getFullYear()} `);
    console.log(`Get day ${date3.getDate()} `);
    
    

    注释

    Runar在公认的回答评论中提到了一些非常重要的事情。要在使用Javascript日期API时获得一致的结果,请使用以下方法: getUTCDate() .这将给我们 1 2000-01-01 getDate() 方法可以给我们一个不同的数字。。。

    0 回复  |  直到 3 年前
        1
  •  3
  •   Rúnar Berg Zebra    3 年前

    根据ECMA标准 Date.parse method :

    发生的事情是 New Date() 在绳子上。这个 "2000-01-01" 版本符合a Date Time String Format

    当您使用 "2000/01/01" 作为输入,标准有以下内容:

    为了获得一致的结果,您可能想看看 Date.UTC

    new Date(Date.UTC(2000, 0, 1))
    

    如果需要传入ISO字符串,请确保包含 +00:00 (通常缩写为 z )

    new Date("2000-01-01T00:00:00Z");
    

    使用等效的UTC setter方法 setUTCHours

    检索日期时,还要确保 使用UTC getter方法 (例如。 getUTCMonth ).

    const date = new Date("2000-01-01T00:00:00Z");
    
    console.log(date.getUTCDate());
    console.log(date.getUTCMonth());
    console.log(date.getUTCFullYear());

    Intl.DatTimeFormat ,只需记住传递 timeZone: "UTC" options .

    const date = new Date("2000-01-01T00:00:00Z");
    const dateTimeFormat =
      new Intl.DateTimeFormat("en-GB", { timeZone: "UTC" });
    
    console.log(dateTimeFormat.format(date));