当前位置: 首页 > news >正文

毫秒生成的时间戳如何转化成东八区具体时间

假设现在有一个时间是1709101071419L

后端代码实现

Java代码(东八区时间)

在Java代码中,我们将时区从UTC调整为东八区(UTC+8):

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;public class TimestampConverter {public static void main(String[] args) {// 时间戳long timestamp = 1709101071419L;// 将时间戳转换为Instant对象Instant instant = Instant.ofEpochMilli(timestamp);// 转换为东八区时间ZonedDateTime dateTimeInBeijing = instant.atZone(ZoneId.of("Asia/Shanghai"));// 创建DateTimeFormatter来格式化时间DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));// 格式化时间为字符串String formattedDate = formatter.format(dateTimeInBeijing);System.out.println("Date and Time in Beijing (UTC+8): " + formattedDate);}
}

这段Java代码中,通过将Instant转换为ZonedDateTime并指定ZoneId.of("Asia/Shanghai"),可以确保时间正确地转换为东八区时间,然后使用DateTimeFormatter进行格式化。

前端代码实现

JavaScript代码(东八区时间)

在JavaScript中,我们可以调整时间戳的显示方式来反映东八区的时间:

// 时间戳
const timestamp = 1709101071419;// 创建一个新的Date对象
const date = new Date(timestamp);// 转换为东八区时间,获取年月日时分秒
const formattedDate = date.toLocaleString("en-US", {timeZone: "Asia/Shanghai"});console.log("Date and Time in Beijing (UTC+8): " + formattedDate);

这段JavaScript代码使用toLocaleString方法和{timeZone: "Asia/Shanghai"}选项来确保日期时间按照东八区时间来显示。

这样,不管是在Java还是JavaScript中,正确地将时间戳转换成了东八区的时间,并进行了格式化显示。
在这里插入图片描述

在这里插入图片描述

http://www.lryc.cn/news/311493.html

相关文章:

  • 02. Nginx入门-Nginx安装
  • leetcode73. 矩阵置零
  • 【中间件】RabbitMQ入门
  • rtt的io设备框架面向对象学习-电阻屏LCD设备
  • 商城免费搭建之java商城 java电子商务Spring Cloud+Spring Boot+mybatis+MQ+VR全景
  • 蓝桥杯刷题--python-16
  • 闰年计算中的计算机Bug
  • python水表识别图像识别深度学习 CNN
  • Java对接快递100实时快递单号查询API接口
  • Redis常见的15个【坑】,避坑指南
  • 04. Nginx入门-Nginx WEB模块
  • Python在信息安全领域中具有重要的作用
  • Linux 定时备份文件到另一台服务器
  • C++输入输出(I\O)
  • 基本设计模式
  • 双通道音频功率放大电路,外接元件少, 通道分离性好,3V 的低压下可正常使用——D2025
  • Linux 内核获取函数size
  • Python+neo4j构建豆瓣电影知识图谱
  • DolphinScheduler——介绍及架构设计
  • 【Python】约瑟夫环问题
  • Python成功解决AttributeError: ‘Series‘ object has no attribute ‘set_value‘
  • 基于springboot+vue的医院药品管理系统
  • Python爬虫——Urllib库-1
  • 瑞_Redis_短信登录(一)
  • 《剑指 Offer》专项突破版 - 面试题 70 : 排序数组中只出现一次的数字(C++ 实现)
  • Linux安全加固功能
  • 最新AI系统ChatGPT网站H5系统源码,支持Midjourney绘画
  • 【服务器数据恢复】昆腾存储中raid5磁盘阵列数据恢复案例
  • 企业微信变更主体怎么改?
  • 常用生理眼电信号整理合集 (EOG)