How to add hours to unix timestamp or epochmilli in java?
This tutorial explains how to add hours to unix timestamp or epochmilli using TimeUnit in Java. You may face situations like adding hours, minutes and seconds to an timestamp for display purpose in UI. Let’s see how to do that.
Add Hours to Timestamp Example
The below example shows you how to add hours, let’s say 5 hours or today’s current hour to the timestamp.
package com.sneppets.app; import java.time.LocalDate; import java.time.ZoneId; import java.util.concurrent.TimeUnit; public class TimestampHoursExample { public static void main (String[] args) { LocalDate date = LocalDate.now(); ZoneId zoneId = ZoneId.systemDefault(); long epochTimestamp = date.atStartOfDay(zoneId).toInstant().toEpochMilli(); System.out.println("epochTimeStamp : " + epochTimestamp); int hoursToAdd = 5; long hourValue = TimeUnit.HOURS.toMillis(hoursToAdd); long finalEpochTimestampWithHoursAdded = epochTimestamp + hourValue; System.out.println("finalEpochTimestampWithHoursAdded : " + finalEpochTimestampWithHoursAdded); }
Output
epochTimeStamp : 1580754600000 finalEpochTimestampWithHoursAdded : 1580772600000
In the above example we have used LocalDate and converted it to epochmilli and tried to add 5 hours timeunit using java.util.concurrent.TimeUnit util.
Now let us check the results and verify whether hour value is added to the timestamp. To verify this you can use any online epochconverter tool as shown below.
epochTimeStamp
finalEpochTimestampWithHoursAdded
java.util.concurrent.TimeUnit
TimeUnit is an enum and it represents time durations at a given unit of granularity. It supports many units like DAYS, MINUTES, SECONDS etc.,
You need to use timeunit HOURS and toMillis() method of TimeUnit to convert the hours value to milliseconds.
Further Reading
- Difference between Spring ApplicationContext and BeanFactory
- Format LocalDate to String or int with Month and Day in double digit
- Where the Docker images are stored locally?
- Check if Element exists in a Collection using Lambda Expressions