How can I format: "2010-07-14 09:00:02"
date to depict just 9:00
?
views:
93answers:
4
+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
2010-08-17 17:08:31
thank u so much!! :) made my day! :)
jillika iyer
2010-08-17 17:10:29
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
2010-08-17 17:20:55
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
2010-08-17 17:22:40
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
2010-08-17 18:38:36
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
2010-08-17 17:08:39
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
2010-08-17 17:10:49
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
2010-08-17 17:11:20
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
2010-08-17 17:10:54