This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes time conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "time conversion" Watch "time conversion" New topic
Author

time conversion

mudassir shahab
Ranch Hand

Joined: Oct 13, 2003
Posts: 54
Hello,
i want to convert time given in am/pm to 24 hr representation and vice versa
like 19:00 should be parsed in to 7:00 PM
similarly 08:00 PM should be displayed as 20:00 .
how can i do it

from db i get it in datetime format using mysql ie ; 2006-05-18 18:30:22
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

You can use SimpleDateFormat to do that. If you get the datetime from the SQL, I assume you can get Timestamp object.



or



If you just want to convert the time in String from one format to another, you might need to build a Calendar object first, then use SimpleDateFormat to convert it.


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
mudassir shahab
Ranch Hand

Joined: Oct 13, 2003
Posts: 54
not working buddy ..see my code ..where is the mistake

String date = "19:00"; // string of date to convert
DateFormat formatIn = new SimpleDateFormat("H:mm");
DateFormat formatOut = new SimpleDateFormat("H:mm a");
Timestamp t = new Timestamp(formatIn.parse(date).getTime());
System.out.println(formatOut.format(new Date(t.getTime())));

output ----> 19:00 PM ......... but the required output is 07:00 PM
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

Actually my reply above is only an example how to use SimpleDateFormat. It's not the solution to your problem. Anyway, here's the solution to your problem.



You don't need to create a Timestamp object. I mentioned the Timestamp object in my previous reply because you mentioned something about retrieving the datetime from mysql. Normally, you will get Timestamp object when retrieving the data from Timestamp.

The formatOut takes "h:mm a" not "H:mm a" if you want to format it in Hour in am/pm (1-12). Check the SimpleDateFormat API for more information.

Do let me know if you have any more questions
[ July 15, 2007: Message edited by: Freddy Wong ]
mudassir shahab
Ranch Hand

Joined: Oct 13, 2003
Posts: 54
its done ..thanks Wong
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: time conversion
 
Similar Threads
Date Problems
SEVERE: BAD packet signature 200,SEVERE: Caught exception (java.lang.NullPointerException)
Timer
Map 2 CMP Entity Beans to 1 table?
Date class question