Get correct local time in java (Calendar)

32,023

Solution 1

  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.

Solution 2

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

Solution 3

I would guess you're getting time zones mixed up. Get Calendar with your system's default locale:

Calendar cal = Calendar.getInstance(Locale.getDefault());
Share:
32,023
Adam Varhegyi
Author by

Adam Varhegyi

I like the color blue. Often eating gyros.

Updated on July 09, 2022

Comments

  • Adam Varhegyi
    Adam Varhegyi almost 2 years

    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?

  • Adam Varhegyi
    Adam Varhegyi over 11 years
    I try this but i must wait afternoon. I will accept your answer if its OK
  • Maroun
    Maroun over 11 years
    @AdamVarhegyi You can simply change time and check it now :)
  • Am_I_Helpful
    Am_I_Helpful almost 9 years
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.
  • Barett
    Barett almost 9 years
    @shekharsuman I disagree. Although it is not correct, this is a perfectly valid, short answer.
  • Barett
    Barett almost 9 years
    Mike, HH is supposed to return values from 0-23, which is what the OP wants. kk returns values 1-24. per docs.oracle.com/javase/7/docs/api/java/text/…
  • Barett
    Barett almost 9 years
    Hmm. This seems to be the same as what the OP is already doing.
  • Maroun
    Maroun almost 9 years
    @Barett Not really.. take another look.
  • Barett
    Barett almost 9 years
    If you're avoiding saying that the construction of the date is the problem (for the second time), it would be helpful to mention that in your answer. Dunno why all the veiled language; this isn't Socratic Overflow. The OP is confused because he assumed that the formatting was the problem. Your formatting is exactly the same, besides punctuation.
  • Maroun
    Maroun almost 9 years
    @Barett I agree, it's not Socratic Overflow. But you're lucky, see this philosophy.stackexchange.com