0

Introduction

I wanted to get my computer's current time in the format of HH:MM:SS. Although I tried a lot of different methods, they are all giving me the same result.

Code

long milliseconds = System.currentTimeMillis(); int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours = (int) ((milliseconds / (1000*60*60)) % 24); System.out.println(hours +":" + minutes+ ":"+ seconds); 

Result

12:42:34 but my computer's current time is 8:42:34

What I want

But the time is different from my computer's current time. Why?

3
  • Use SimpleDateFormat. Commented Aug 11, 2013 at 13:01
  • Head First Java is a GREAT starter book for those with some OO background but want to learn basics of Java. It has a great chapter on formatting for multiple inputs and included many calls for date and time as well as the use of Date vs Calendar. Commented Aug 11, 2013 at 13:08
  • Also, it seems to me your output is due to time zone. Most millisecond calls are based is Eastern Time Zone Commented Aug 11, 2013 at 13:10

4 Answers 4

2

Try this:

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime())); 
Sign up to request clarification or add additional context in comments.

Comments

2

The currentTimeMillis method returns time in UTC time. Use a SimpleDateFormat instance to format the time in your current TimeZone.

Comments

2

Try this code

DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date)); 

use hh:mm:ss format for getting hour in am/pm (1-12) .
use HH:mm:ss format for getting hour in 24 hour format .
For more details SimpleDateFormat

1 Comment

Is there any credence to adding some String.format calls? Like %td for day or %tB for month? Also, the use of the < operand for multiple formats for a single input? I ask because it was discussed in a basics book I read.
1

Try dis

 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //get current date time with Date() Date date = new Date(); System.out.println(dateFormat.format(date)); //get current date time with Calendar() Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime())); 

2 Comments

I've read that date has mostly been superceded by calendar, has this been your experience? Or is it just a matter of which one fits the bill? I ask because a book I finished reading seems to highly favor Calendar.
@JeremyJohnson Date is simply a wrapper around a UNIX timestamp. Calendar stores TimeZone information and whatnot. Whichever fits the bill really.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.