java time to string,how to convert String to Date and Time in Java

原文:

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?

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值