如何使用JavaScript获取给定日期和时区的午夜(一天的开始)的unix时间戳?

uqcuzwp8  于 2023-04-28  发布在  Java
关注(0)|答案(2)|浏览(115)

是否可以创建一个JavaScript函数,返回给定日期和时区的一天开始的unix时间戳?如果是,如何?
这不仅仅是将日期字符串转换为时间戳。它必须将时区带入帐户。
我做了很多尝试,但都失败了。
例如

getMidnightTimestamp('2023-04-10','Australia/Sydney');

这是我尝试过的,但由于某种原因,它返回无效的时间戳。

function getMidnightTimestamp(date, timezone) {
    // Parse the input date
    const inputDate = new Date(date);

    // Set the input date to midnight
    inputDate.setHours(0, 0, 0, 0);

    // Create an Intl.DateTimeFormat object with the given timezone
    const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
        timeZone: timezone,
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
    });

    // Format the input date to a string in the specified timezone
    const dateString = dateTimeFormat.format(inputDate);

    // Parse the formatted date string back to a Date object
    const midnightDate = new Date(dateString);

    // Return the timestamp in milliseconds
    return midnightDate.getTime()/1000;
}

console.log(getMidnightTimestamp('2023-04-10','Australia/Sydney'));
gev0vcfq

gev0vcfq1#

您可以尝试使用Date.prototype.toLocaleString() method解析时区信息:

function getMidnightTimestamp(date, timeZone) {
  // We first try to create it using UTC timezone just to obtain the correct timezone info that includes DST
  const rawOffset = new Date(`${date}T00:00:00.000+00:00`)
    .toLocaleString('en-US', {
      timeZone,
      timeZoneName: 'shortOffset'
    })
    .split('GMT')[1]; // Then we parse the timezone info using the back of the generated string such as GMT+12:45
  const sign = rawOffset[0] || '+';
  const [hour = '', minute = ''] = rawOffset.substring(1).split(':');
  // Lastly we construct the full ISO date string to obtain the midnight Date / timezone for that region
  const midnightDate = new Date(`${date}T00:00:00.000${sign}${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`);
  return midnightDate.getTime() / 1000;
}

// Sample
console.log(getMidnightTimestamp('2023-04-10','Australia/Sydney'));
toiithl6

toiithl62#

由于MDN
JavaScript Date对象以独立于平台的格式表示时间上的单个时刻。Date对象封装了一个整数,表示自UTC(纪元)1970年1月1日午夜起的毫秒数。
所以,你应该只根据指定的时区设置时间,并将其转换成数字;默认情况下,它将转换为UNIX时间戳格式。
代码如下:

function getMidnightTimestamp (date, timeZone) {
  
  let date$ = new Date( date );

  date$ = new Date( date$.toLocaleString("en-US",{timeZone}) )

  return Number( date$ ) / 1000; // we divided by 1000 because it returns the UNIX timestamp in milliseconds and the standard is seconds-based format
  
}

const timestamp = getMidnightTimestamp('2023-04-10','Australia/Sydney');

console.log(timestamp);

相关问题