将时间戳日期转换为Unix时间戳

huangapple 未分类评论51阅读模式
英文:

converting timestamp date to unix timestamp

问题

i have data like this one 
date what i got from timestamp utc are : 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);

i need to get timestamp number like 2020-06-29 05:31:58
and convert it become unix timestamp like this one 1593408718
how to convert it ?
英文:

i have data like this one
date what i got from timestamp utc are : 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);

i need to get timestamp number like 2020-06-29 05:31:58
and convert it become unix timestamp like this one 1593408718
how to convert it ?

答案1

得分: 0

阅读了您的问题后,我假设您的方法 message.getHeader().getUtcTimeStamp(SendingTime.FIELD) 返回一个 String(而不是 LocalDateTime),表示UTC时间戳,格式类似于 2020-06-29 05:31:58.1532020-06-29 05:31:58

由于您展示了不同格式的日期时间(分别是不同精度的日期时间),您需要通过定义适当的 DateTimeFormatter 来处理这些情况,该格式能够处理可选的毫秒部分(yyyy-MM-dd HH:mm:ss[.SSS])。

您可以按照以下方式使用它:

public static void main(String[] args) {
	// 假设这只是一个示例,接收来自您的消息的结果
	String utcTimestamp = "2020-06-29 05:31:58";
	// 通过将字符串解析为 LocalDateTime 并添加时区,创建一个 ZonedDateTime
	ZonedDateTime zdt = LocalDateTime.parse(utcTimestamp,
								DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))
						 .atZone(ZoneId.of("UTC"));
	// 然后获取纪元毫秒数 / Unix 时间戳
	long millis = zdt.toInstant().toEpochMilli();
	// 并打印结果
	System.out.println(zdt + " ==> " + millis + " epoch millis");
}

当然,这个示例的输出对于仅精确到秒的日期时间是不同的:

  1. 2020-06-29T05:31:58Z[UTC] ==> 1593408718000 纪元毫秒
  2. 2020-06-29T05:31:58.153Z[UTC] ==> 1593408718153 纪元毫秒

如果您调用 long seconds = zdt.toEpochSecond() 而不是转换为 toInstant().toEpochMillis(并稍微调整输出),您将得到相同的值:

public static void main(String[] args) {
	// 假设这只是一个示例,接收来自您的消息的结果
	String utcTimestamp = "2020-06-29 05:31:58.153";
	// 通过将字符串解析为 LocalDateTime 并添加时区,创建一个 ZonedDateTime
	ZonedDateTime zdt = LocalDateTime.parse(utcTimestamp,
								DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))
						 .atZone(ZoneId.of("UTC"));
	// 然后获取纪元秒数
	long seconds = zdt.toEpochSecond();
	// 并打印结果
	System.out.println(zdt + "\t==> " + seconds + " epoch seconds");
}

输出:

  1. 2020-06-29T05:31:58Z[UTC] ==> 1593408718 epoch seconds
  2. 2020-06-29T05:31:58.153Z[UTC] ==> 1593408718 epoch seconds

如果您的方法确实返回 LocalDateTime,您可以简单地跳过转换,写成:

public static void main(String[] args) {
	LocalDateTime utcDateTime = message.getHeader().getUtcTimeStamp(SendingTime.FIELD); 
	// 然后获取纪元秒数
	long seconds = utcDateTime.atZone(ZoneId.of("UTC")).toEpochSecond();
	// 并打印结果
	System.out.println(utcDateTime + "\t==> " + seconds + " epoch seconds");
}
英文:

Having read your question, I assume your method message.getHeader().getUtcTimeStamp(SendingTime.FIELD) returns a String (not a LocalDateTime) representing a timestamp in UTC while being formatted either like 2020-06-29 05:31:58.153 or 2020-06-29 05:31:58.

Since you have (shown) differently formatted datetimes (respectively, datetimes with a different accuracy), you will have to take care of that by defining a suitable DateTimeFormatter using a pattern able to deal with optional milliseconds (yyyy-MM-dd HH:mm:ss[.SSS]).

You can use it as follows:

public static void main(String[] args) {
	// receive the result from your message, this is just an example
	String utcTimestamp = "2020-06-29 05:31:58";
	// create a ZonedDateTime by parsing the String to a LocalDateTime and adding a time zone
	ZonedDateTime zdt = LocalDateTime.parse(utcTimestamp,
								DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))
						 .atZone(ZoneId.of("UTC"));
	// then get the epoch milliseconds / unix timestamp
	long millis = zdt.toInstant().toEpochMilli();
	// and print the result
	System.out.println(zdt + " ==> " + millis + " epoch millis");
}

The output of this is, of course, different for datetimes that are only equal down to seconds:

  1. 2020-06-29T05:31:58Z[UTC] ==> 1593408718000 epoch millis
  2. 2020-06-29T05:31:58.153Z[UTC] ==> 1593408718153 epoch millis

If you call long seconds = zdt.toEpochSeconds() instead of converting toInstant().toEpochMillis (and adjust the output a little) you will get the same value for both examples:

public static void main(String[] args) {
	// receive the result from your message, this is just an example
	String utcTimestamp = "2020-06-29 05:31:58.153";
	// create a ZonedDateTime by parsing the String to a LocalDateTime and adding a time zone
	ZonedDateTime zdt = LocalDateTime.parse(utcTimestamp,
								DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))
						 .atZone(ZoneId.of("UTC"));
	// then get the epoch seconds
	long seconds = zdt.toEpochSecond();
	// and print the result
	System.out.println(zdt + "\t==>\t" + seconds + " epoch seconds");
}

Output:

  1. 2020-06-29T05:31:58Z[UTC] ==> 1593408718 epoch seconds
  2. 2020-06-29T05:31:58.153Z[UTC] ==> 1593408718 epoch seconds

If your method really returns a LocalDateTime, you could simply skip conversions and write

public static void main(String[] args) {
	LocalDateTime utcDateTime = message.getHeader().getUtcTimeStamp(SendingTime.FIELD); 
	// then get the epoch seconds
	long seconds = utcDateTime.atZone(ZoneId.of("UTC")).toEpochSecond();
	// and print the result
	System.out.println(utcDateTime + "\t==>\t" + seconds + " epoch seconds");
}

答案2

得分: 0

如果你的 getUtcTimeStamp 方法足够有帮助,可以返回一个 LocalDateTime,那么你已经完成了大部分工作。使用 ldt.atOffset(ZoneOffset.UTC) 将其转换为 Instant(如果你的 getUtcTimeStamp 已经知道它是在 UTC 时间),然后只需调用 toEpochSecond()(如果你想要毫秒部分,可以使用 toEpochMilli(),但你刚刚展示了整秒)。

英文:

If your getUtcTimeStamp method is helpful enough to return a LocalDateTime, you're most of the way there. Convert to an Instant using ldt.atOffset(ZoneOffset.UTC) (your getUtcTimeStamp really should be doing this for you if it already knows it's in UTC), then just call toEpochSecond() (or toEpochMilli() if you want the milliseconds part, but you just showed whole seconds).

答案3

得分: 0

以下是您要翻译的内容:

其他答案都很好。这是我的变种。首先声明一个用于解析的格式化程序:

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.1532020-06-29 05:31:58,即带有和不带有秒分数的时间,以及带有1到9位小数的时间。在格式化程序中重用ISO_LOCAL_TIME使我们能够实现这一点。

英文:

The other answers are fine. Here’s my variant. First declare a formatter for parsing:

private DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
		.append(DateTimeFormatter.ISO_LOCAL_DATE)
		.appendLiteral(' ')
		.append(DateTimeFormatter.ISO_LOCAL_TIME)
		.toFormatter();

Consider declaring the formatter static and/or final. With this formatter I’d do:

	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);

Output is what you asked for:

> 1593408718

The nice thing about the formatter is that it accepts both 2020-06-29 05:31:58.153 and 2020-06-29 05:31:58, that is, time both with and without fraction of second, and with any fraction of from 1 up to 9 decimals. Reusing ISO_LOCAL_TIME in the formatter buys us this.

huangapple
  • 本文由 发表于 2020年6月29日 14:09:53
  • 转载请务必保留本文链接:https://java.coder-hub.com/62632205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定