tags:

views:

93

answers:

4

How can I format: "2010-07-14 09:00:02" date to depict just 9:00?

+6  A: 

Use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat (click the blue code link for the Javadoc).

Here's a kickoff example:

String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
BalusC
thank u so much!! :) made my day! :)
jillika iyer
hi is it also possible to format it in hours:min if I have a unixtimestamp like: 1279080000 ??I tried what was suggested in previous posts but did not help.Thank you
jillika iyer
You can construct a new `Date` object with timestamp in milliseconds and then just format it. If you're actually retrieving it from DB, you should use `ResultSet#getTimestamp()` to get a `Date` as answered in [one of your previous questions](http://stackoverflow.com/questions/3473421/). Or even better, make use of the SQL builtin date/time functions to return the timestamp already in the desired format so that there's no need for the expensive task of remassaging the data of every row afterwards in Java. In that case, just get the hour by `ResultSet#getString()`. Use the right tool for the job
BalusC
i am getting it from the database.but needed to generate a print report. so thought i could iterate on the values and change them on the fly.as i need to just print it out in the end. unable to get it done in any starightforward way :(
jillika iyer
A: 

I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.

Dante617
Wouldn't `H:mm` be a more sane choice?
Joey
Even if the String is *not* a `Date` object initially, you can use `SimpleDateFormat.parse()` to turn it into one, as per BalusC's example.
Andrzej Doyle
Indeed, without AM/PM marker (`a`), you'd rather prefer `H` above `h` to avoid ambiguity between 9:00 (AM) and 9:00 (PM).
BalusC
Good correction. Thanks.
Dante617
A: 

By using a SimpleDateFormatter

Amir Afghani
A: 
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Adam