是否可以创建一个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'));
2条答案
按热度按时间gev0vcfq1#
您可以尝试使用
Date.prototype.toLocaleString()
method解析时区信息:toiithl62#
由于MDN
JavaScript Date对象以独立于平台的格式表示时间上的单个时刻。Date对象封装了一个整数,表示自UTC(纪元)1970年1月1日午夜起的毫秒数。
所以,你应该只根据指定的时区设置时间,并将其转换成数字;默认情况下,它将转换为UNIX时间戳格式。
代码如下: