Get the correct local time in java (Calendar)

I use this method to get local time:

Calendar cal = Calendar.getInstance(); String time= new SimpleDateFormat("dd MMM yyyy HH:mm:ss").format(cal.getTime()); 

My problem is that in the afternoon this method returns me, for example, "11:15", but already "23:15". I hope my desc does not confuse.

I want to get back daily values, such as: 12: MM, 13: MM, 14: MM..etc goes to 23: MM.,.

What should i change?

+4
source share
4 answers
  • Are you sure that the time on the PC or what you use for programming is right?

  • Try using the Gregorian calendar:

     new GregorianCalendar().getTime() 
  • Make sure you have the import:

     import java.util.Date; import java.util.GregorianCalendar; 

Hope this helps.

+4
source

You can try something like this:

 Date date=new Date(); System.out.println(new SimpleDateFormat("yyyy.MM.dd HH:mm").format(date)); 

Output Example:

2013.03.05 22:07

+2
source

I would suggest that you mixed up time zones. Get the calendar with the default locale of your system:

 Calendar cal = Calendar.getInstance(Locale.getDefault()); 
+1
source

You use the HH flags. Use the kk flags instead.

For example, kk:mm instead of HH:mm .

0
source

All Articles