Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any function like "strptime" in java

Tags:

java

suppose there is a time_string like: "wallclock(2011-09-22T01:52:00)"

in C language, I can use "strptime(time_string, "wallclock(%Y-%m-%dT%H:%M:%S)", &tm)"

to get date time and store it into the struct tm,

and then use mktime(&tm) to get the date in seconds

But in Java, I find no way about how to transfer string "wallclock(2011-09-22T01:52:00)",

is there any way to do this job? thank you :-)

like image 811
Nail Avatar asked Aug 25 '26 08:08

Nail


2 Answers

You can either use SimpleDateFormat:

DateFormat format = new SimpleDateFormat("'wallclock('yyyy-MM-dd'T'HH:mm:ss')'");
Date parsed = format.parse(text);

(Note that you probably want to set the time zone of format appropriately.)

Or preferrably (IMO) use Joda Time to do the parsing:

String pattern = "'wallclock('yyyy-MM-dd'T'HH:mm:ss')'";
DateTimeFormatter formatter = DateTimeFormatter.forPattern(pattern);
LocalDateTime localDateTime = formatter.parseLocalDateTime(text);

This will parse to a LocalDateTime which doesn't have a time zone.

In Java 8, you'd use java.time.format.DateTimeFormatter instead.

like image 50
Jon Skeet Avatar answered Aug 27 '26 23:08

Jon Skeet


SimpleDateFormat will get you pretty close.

like image 22
NPE Avatar answered Aug 27 '26 21:08

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!