Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get 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 afternoon this method gives me back for example "11:15" but it is "23:15" already. I hope my desc is not confusing.

I want to get back afternoon values like: 12:MM , 13:MM, 14:MM ..etc goes to 23:MM. . .

What should i change?

like image 814
Adam Varhegyi Avatar asked Mar 05 '13 07:03

Adam Varhegyi


People also ask

How do I get current time in LocalDateTime?

now() now() method of a LocalDateTime class used to obtain the current date-time from the system clock in the default time-zone. This method will return LocalDateTime based on system clock with default time-zone to obtain the current date-time.

What does date () getTime () do in Java?

The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object.

How do I find the current date on LocalDate?

now() now() method of a LocalDate class used to obtain the current date from the system clock in the default time-zone. This method will return LocalDate based on system clock with default time-zone to obtain the current date.

How do I get the current time in Java 8?

You can get the time from the LocaldateTime object using the toLocalTime() method. Therefore, another way to get the current time is to retrieve the current LocaldateTime object using the of() method of the same class. From this object get the time using the toLocalTime() method.


2 Answers

  1. Are you sure that the time on the PC or whatever you are using to program is correct?

  2. Try using the Gregorian calendar:

    new GregorianCalendar().getTime()
    
  3. Make sure you have these imports:

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

Hope that helps.

like image 150
Kersy Avatar answered Oct 23 '22 16:10

Kersy


You can try something like that:

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

Output example:

2013.03.05 22:07

like image 39
Maroun Avatar answered Oct 23 '22 16:10

Maroun