简体   繁体   中英

how to convert timestamp string to java.util.Date

I need to convert a timestamp string to java.util.Date . Eg:

MMDDYYHHMMSS to MM-DD-YY HH-MM-SS

Where MM is month, DD is date, YY is year, HH is hours, MM is minutes and SS is seconds.

You can do it like this:

DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");

but I would strongly recommend that you use Joda Time instead. It's a better date/time library by a long, long way. In particular, the formatters/parsers in Joda Time are thread-safe, so you can reuse them freely and statically; java.text.SimpleDateFormat isn't thread-safe, so you either need to create one per thread or serialize access to it with a synchronized block.

tl;dr

java.time.LocalDateTime.parse(
    "012318123456" ,
    DateTimeFormatter.ofPattern( "MMdduuHHmmss" )
).format( 
    DateTimeFormatter.ofPattern( "MM-dd-uu HH-mm-ss" )
)

01-23-18 12-34-56

java.time

The modern approach uses the java.time classes.

Define a formatting pattern to match your input string.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMdduuHHmmss" ) ;

Your two-digit year will be interpreted as being 21st century ( 20xx ).

Parse as a LocalDateTime because your input string lacks any indicator of time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( "012318123456" , f ) ;

ldt.toString(): 2018-01-23T12:34:56

Generate a string in your desired format.

DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "MM-dd-uu HH-mm-ss" ) ;
String output = ldt.format( fOut  );

01-23-18 12-34-56

ISO 8601

Both of your formats are terrible, for multiple reasons.

When serializing date-time values, use the standard ISO 8601 formats whenever possible. They are designed to be practical, easy to parse by machine, easy to read by humans across cultures.

For a date-time time such as yours, the T in the middle separates the date portion from the time-of-day portion.

2018-01-23T12:34:56


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

使用带有适当格式字符串的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