How to format Time not Date on Android or Java?

I want to format the time as follows: 2011-05-11 11:22:33 .

I had the following code:

 Time time = new Time(MobiSageUtility.TIMEZONE_STRING); time.setToNow(); String timeStr= time.format("yyyy-MM-dd HH:mm:ss"); 

However, this gives a date like: "yyyy-MM-dd HH:mm:ss" not "2011-05-11 11:22:33" . Looking at the Android help docs, I tried the following code:

  String timeStr = time.format2445(); 

But this gives a line like: 20110511T112233 . Can someone tell me how to format time correctly?

+4
source share
4 answers

Use date instead of time, and then use SimpleDateFormat.

Example:

 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String dateString = fmt.format(date); 

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

+4
source

String timeStr = time.format ("% Y:% m:% d% H:% M:% S");

See man strftime in the doc format of the method format:

http://linux.die.net/man/3/strftime

+23
source

Use SimpleDateFormater

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String time = sdf.format(date); 
+2
source
 SimpleDateFormat outFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(milliseconds); String dateString = outFmt.format(date); 
0
source

All Articles