What is the best way to subtract 5 minutes from a given epoch date ?
public long fiveMinutesAgo(String epochDate) {
//ToDo
return fiveMinBack;
}
What is the best way to subtract 5 minutes from a given epoch date ?
public long fiveMinutesAgo(String epochDate) {
//ToDo
return fiveMinBack;
}
epochDate has to be a Date. Use a Calendar:
Calendar calendar = Calendar.getInstance();
calendar.setTime(epochDate);
calendar.add(Calendar.MINUTE, -5);
Date result = calendar.getTime();
You can use any of the above mentioned methods by other user , but if interested give a try to
Java 8 Date and Time API
public void subtract_minutes_from_date_in_java8 ()
{
LocalDateTime newYearsDay = LocalDateTime.of(2015, Month.JANUARY, 1, 0, 0);
LocalDateTime newYearsEve = newYearsDay.minusMinutes(1);// In your case use 5 here
java.time.format.DateTimeFormatter formatter =java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss S");
logger.info(newYearsDay.format(formatter));
logger.info(newYearsEve.format(formatter));
}
Output :
01/01/2015 00:00:00 CST
12/31/2014 23:59:00 CST
Class LocalDateTime is an immutable date-time object present in java.time package in Java 8 that represents a date-time, often viewed as year-month-day-hour-minute-second.
Below is the syntax of of()
method used :
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)
which obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.
Here's a body for your method:
private static final long FIVE_MINS_IN_MILLIS = 5 * 60 * 1000;
public long fiveMinutesAgo(String epochDate) throws ParseException {
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
long time = df.parse(epochDate).getTime();
return time - FIVE_MINS_IN_MILLIS;
}
The time is in millis-since-the-epoch, so to find out five minutes before you simply have to subtract 5 mins in milliseconds (5 * 60 * 1000).
I would suggest renaming the method to: fiveMinutesBefore()
and perhaps breaking it into two methods: one for parsing string dates into times and the other for subtracting minutes from the time.
You might also consider using Joda-Time as it's much better designed (and thread-safer) than the standard Java date package.
You can subtract 5 minute equivalent of miiliseconds from date you get:-
//convert input string epochDate to Date object based on the format
long ms=date.getTime();
Date updatedDate=new Date(ms - (5 * 60000)); //60000 is 1 minute equivalent in milliseconds
return updatedDate.getTime();