Rolando Rolando - 10 months ago 45
Java Question

How to convert 24hr timestring to standard java Date vice versa?

I would like to have two functions:

  1. Say I have the date in a string
    and time in a String:
    . I would like a simple function (if possible) that takes two parameters (the date and time from above) in java that converts it into 11/12/2011 2:00AM in a Java

  2. Say I have a java
    object as the only parameter (e.g. 11/12/2011 2:00AM) that returns the military time from it, (e.g. "0200").

Is there some java library or what is the best way to accomplish the above? Or is there something built into java Date that makes it easy to get something in military time to normal time Java date uses?

Answer Source
new SimpleDateFormat("MM/dd/yyyy HHmm").parse("11/12/2011" + " " + "0200");
new SimpleDateFormat("MM/dd/yyyy HHmm").format(new Date());
new SimpleDateFormat("HHmm").format(new Date());

(assuming the military in the US still put month first in dates).

[edit: you need to worry about your time zone too - for parsing it's often easiest to simply append this. for example:

new SimpleDateFormat("MM/dd/yyyy HHmm Z").parse("11/12/2011" + " " + "0200" + " PST");

(maybe the military always use UTC? i have no idea...). and for formatting, you can set the timezone on the SDF instance using setTimezone().]