javascript - 如何在 Javascript 中格式化时间戳以显示相关时区的正确时间
问题描述
我在 JavaScript 中处理时间时遇到问题。我在 firebase 的文档中有一个时间戳,并且我有一个应该发送通知的云功能。我想发送带有正确格式为英国当前时区(当前是 BST 或 UTC+1 或 GMT+1)的时间戳的通知。下面是我的代码...
exports.sendNotificationNewRota = functions.firestore
.document('rota/{attendanceId}')
.onCreate(async snapshot => {
const transaction = snapshot.data();
var dateIn = transaction.timeIn.toDate();
let timeIn = dateIn.toLocaleTimeString( {
timezone: 'Europe/London',
timeZoneName: 'long',
hour: '2-digit',
minute:'2-digit'});
console.log(timeIn);
此代码的输出为我提供了 UTC 时间。当 BST 完成但不是现在,这可能会很好。有没有办法正确处理时间?
谢谢
解决方案
注意函数签名Date.prototype.toLocaleTimeString()
dateObj.toLocaleTimeString([locales[, options]])
详情在这里
您有效地将配置传递给locales
参数,要使代码正常工作,您需要添加一个空的第一个参数。或者,您也可以指定它'en-UK'
,例如:
exports.sendNotificationNewRota = functions.firestore
.document('rota/{attendanceId}')
.onCreate(async snapshot => {
const transaction = snapshot.data();
var dateIn = transaction.timeIn.toDate();
let timeIn = dateIn.toLocaleTimeString([],{ //<-- fix here
timezone: 'Europe/London',
timeZoneName: 'long',
hour: '2-digit',
minute:'2-digit'});
console.log(timeIn);
推荐阅读
- ruby-on-rails - elasticsearch 模型更新到 7.0 中断测试
- javascript - AWS S3 js SDK:CORS 策略已阻止从源访问 XMLHttpRequest
- internet-explorer - Internet Explorer 检查模式
- java - 用一些规则替换嵌套字符串
- html - 为什么 *ngIf 不能在 Angular 中使用 ng-container
- c++ - const 的 static_cast 抛弃限定符
- java - 如何在 Java 中使用观察者模式?
- c - 为什么取消引用 C 中的引用?在 * 旁边使用 &
- command-line - 如何使用 InstallShield 安装 Crystal Report 静默模式?
- c++ - 指令覆盖先前的结果