java - 将时间戳日期转换为 unix 时间戳
问题描述
我有这样一个日期的数据,我从时间戳 UTC 得到的是:2020-06-29 05:31:58.153
LocalDateTime timestampasstring = message.getHeader().getUtcTimeStamp( SendingTime.FIELD);
Timestamp timestamp = Timestamp.from(timestampasstring.toInstant(ZoneOffset.UTC));
System.out.println(timestamp);
String timestampstrings = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
String timestampstrings2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(timestamp);
我需要获取像 2020-06-29 05:31:58 这样的时间戳编号并将其转换为像这样的 unix 时间戳 1593408718 如何转换它?
解决方案
其他答案都很好。这是我的变种。首先声明一个用于解析的格式化程序:
private DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();
考虑声明格式化程序static
和/或final
. 使用这个格式化程序,我会这样做:
String timestampAsString = "2020-06-29 05:31:58.153";
OffsetDateTime dateTime = LocalDateTime
.parse(timestampAsString, timestampFormatter)
.atOffset(ZoneOffset.UTC);
long unixTimestamp = dateTime.toEpochSecond();
System.out.println(unixTimestamp);
输出是您要求的:
1593408718
格式化程序的好处是它同时接受2020-06-29 05:31:58.153
和2020-06-29 05:31:58
,也就是说,时间有和没有秒的分数,以及从 1 到 9 位小数的任何分数。在格式化程序中重用ISO_LOCAL_TIME
为我们买了这个。
推荐阅读
- python-3.x - TypeError:Interval 类型的对象在 Plotly、Python 中不是 JSON 可序列化的
- string - MIPS:如何获取字符串的第 5 个字节并用它替换不同字符串的第 4 个字节?
- python - 为什么有多个输入层?GraphSAGE
- python - 转换数据帧“to_csv”时如何在数值前面填充零?
- android - 在 Appcelerator Studio 中运行项目时出错
- xamarin.forms - ITMS-90809:不推荐使用的 API 使用 - Apple 将停止接受使用 UIWebView API 的应用程序的提交
- if-statement - 如何根据其他单元格值在具有背景颜色计数的谷歌工作表中计数或 sumif
- docx4j - 在最新版本的 xlsx4j 中为空 JaxbSmlPart
- vue.js - 处理 vue 中的组件的最佳解决方案是什么?
- android-studio - 当我尝试同步 Gradle 文件时出现以下错误:错误:无法解决:android.recyclerview:recyclerview: Affected Modules: app