Jack
Jack

Reputation: 115

How to get my current time

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?

Upvotes: 0

Views: 127

Answers (4)

Juned Ahsan
Juned Ahsan

Reputation: 68725

Try this:

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

Upvotes: 2

Developer
Developer

Reputation: 6350

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()));

Upvotes: 1

Prabhaker A
Prabhaker A

Reputation: 8483

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

Upvotes: 2

jtahlborn
jtahlborn

Reputation: 53694

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

Upvotes: 2

Related Questions