Amit Das
Amit Das

Reputation: 1107

How to get current hour in milliseconds format in java?

How to get current hour as a count of milliseconds since epoch?

Like if the time is 4:20 a.m. Then how to get current hour in milliseconds so that it will represent 4:00 a.m.

Upvotes: 2

Views: 3470

Answers (4)

MadProgrammer
MadProgrammer

Reputation: 347332

With Java 8...

LocalDateTime ldt = LocalDateTime.of(2015, Month.MAY, 4, 4, 30);
ldt = ldt.withMinute(0).withSecond(0).withNano(0);
long millisSinceEpoch = ldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

The basic idea would be to take the "time" zero out the elements you don't want and convert the result to milliseconds...

Also...

If you don't like typing, you could use...

ldt = ldt.truncatedTo(ChronoUnit.HOURS);

instead of ldt = ldt.withMinute(0).withSecond(0).withNano(0)

Upvotes: 5

Basil Bourque
Basil Bourque

Reputation: 340230

In Joda-Time 2.7, on a DateTime object call the getMillisOfSecond method to return an int.

int millisOfSecond = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).getMillisOfSecond() ;

Upvotes: 1

Pedro Mestre Silva
Pedro Mestre Silva

Reputation: 154

Long time = System.currentTimeMillis();
time = time / 3600000;
time = time * 3600000;

or a shorter version:

Long time = (System.currentTimeMillis()/3600000)*3600000;

Note: 3600000 = 60 minutes * 60 seconds * 1000 milisecs.

Rationale: when you do the first integer division by 3600000 you'll "lose" the information about minutes, seconds and milliseconds. However the result is in hours, not in milliseconds. To have the time back in milliseconds simply multiply by 3600000.

At the first sight it might look that dividing by 3600000 and multiplying 3600000 will be equivalent to "do nothing", but because of integer arithmetic the result is what you want (get rid of the minutes, seconds and milliseconds information).

Upvotes: 4

Veselin Davidov
Veselin Davidov

Reputation: 7081

You can try like that.

Calendar c = Calendar.getInstance(); //Get current time
//set miliseconds,seconds,minutes to 0 so we get exactly the hour 
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MINUTE, 0);
// This gets the time in milliseconds
long result=c.getTime().getTime();

Upvotes: 4

Related Questions