简体   繁体   中英

Convert a long string of date and time into Timestamp format in Java

I recently received an unlabeled field in the metadata I'm working with.

The data in it all looks like this:

20160305111235.703000

20101030120530.703000

I suspect that they are just a long string made by date and time combined.

The best way in order to work with these strings in my project seems to be converting such strings to the Timestamp format "yyyy-MM-dd hh:mm:ss.SSS"

Is there an good way to convert to this format? I am using substring to add the "-" and ":" to the string, but is there a better way?

Thanks.

Use the java.time classes built into Java 8 and later: LocalDateTime and DateTimeFormatter .

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddkkmmss.SSSSSS") ;
LocalDateTime ldt = LocalDateTime.parse("20160305111235.703000", formatter);

Dump to console.

System.out.println(ldt);

2016-03-05T11:12:35.703

You can use SimpleDateFormat to do it. There is description by link. Also you can google for a lot of examples how to use it.

So you just need to convert value in your data to Date and then format it using SimpleDateFormat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM