javaparsingdatedatetimetime

How to parse times in Java?


I was wondering if java comes with a built in way to parse times/dates like this one:

5m1w5d3h10m15s

It's 5 months, 1 week, 5 days, 3 hours, 10 minutes, 15 seconds.


Solution

  • Yes, it's called SimpleDateFormat, you just have to define your pattern.

    As you didn't (voluntarly?) precise the year, I added one :

    DateFormat df = new SimpleDateFormat("M'm'W'w'F'd'H'h'm'm's's'yyyy");
    System.out.println(df.parse("5m1w5d3h10m15s"+"2012"));
    

    Of course there are some libraries available (many people redirect to Joda, which is better than the standard and confusing java libraries) but as your question is about "if java comes with a built in way to parse times/dates", the answer is a clear yes.