如何在Java中将字符串转换为日期和时间

huangapple go评论78阅读模式
英文:

how to convert String to Date and Time in Java

问题

我知道这实际上是一个初学者问题,但似乎我找不到任何解决方法。

因此,我有一个从JSON数据库网站获取的字符串:

DateTime = "\/Date(1598036400000)\/"

但问题是,如何将这个字符串转换为实际的日期时间?

英文:

I know this is really a beginner question, but it seems I can't find any good solution for this.

So I have a String that I get from a JSON database website that is:

DateTime = "\/Date(1598036400000)\/" 

But the question is how do I convert this String to a real DateTime?

答案1

得分: 3

你需要执行几个步骤,因为原始表示中的值不是 long 类型,而是 "/Date(1598036400000)/"。该 String 内部的数字值表示的是时刻的纪元毫秒数,你需要移除其余的字符或子字符串。以下是一个示例...

public static void main(String[] args) {
	// 获取原始 String 值,
	String datetime = "/Date(1598036400000)/";
	// 移除所有非数字的字符,
	String millisStr = datetime.replace("/", "").replace("Date(", "").replace(")", "");
	// 然后将其转换为 long 类型,
	long millis = Long.valueOf(millisStr);
	// 并从 long 创建一个时刻(Instant)
	Instant instant = Instant.ofEpochMilli(millis);
	// 最后使用该时刻在特定时区创建一个时间点 (ZonedDateTime)
	ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.of("CET"));
	// 并打印其默认的 String 表示
	System.out.println(zdt);
}

... 输出结果为

2020-08-21T21:00+02:00[CET]

如果你需要不同格式的 String,你可以使用 DateTimeFormatter,甚至考虑不同的语言或地区。以下是使用德语区域设置输出结果的示例:

System.out.println(zdt.format(
		DateTimeFormatter.ofPattern("EEEE, dd. MMMM yyyy HH:mm:ss", Locale.GERMAN))
);

输出结果为

Freitag, 21. August 2020 21:00:00
英文:

You will have to perform several steps due to the value not being a long in its original representation "/Date(1598036400000)/". The numeric value inside that String is representing a moment in time in epoch milliseconds and you have to remove the remaining characters or substrings. Here's an example...

public static void main(String[] args) {
	// take the original String value,
	String datetime = "/Date(1598036400000)/";
	// remove anything that isn't a digit,
	String millisStr = datetime.replace("/", "").replace("Date(", "").replace(")", "");
	// then convert it to a long,
	long millis = Long.valueOf(millisStr);
	// and create a moment in time (Instant) from the long
	Instant instant = Instant.ofEpochMilli(millis);
	// and finally use the moment in time to express that moment in a specific time zone 
	ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.of("CET"));
	// and print its default String representation
	System.out.println(zdt);
}

... which outputs

2020-08-21T21:00+02:00[CET]

If you need a differently formatted String, you can use a DateTimeFormatter that even considers different locales or languages.
The output of

System.out.println(zdt.format(
		DateTimeFormatter.ofPattern("EEEE, dd. MMMM yyyy HH:mm:ss", Locale.GERMAN))
);

is

Freitag, 21. August 2020 21:00:00

huangapple
  • 本文由 发表于 2020年8月21日 19:46:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63522335.html
匿名

发表评论

匿名网友

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

确定