1

What is the best way to subtract 5 minutes from a given epoch date ?

public long fiveMinutesAgo(String epochDate) {
//ToDo
return fiveMinBack;
}
Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
Sachin
  • 449
  • 2
  • 9
  • 27
  • 3
    Your input is a `String` - what's the format? You should separate tasks into parsing, then arithmetic. Which of those is giving you a problem? – Jon Skeet Jan 28 '15 at 10:33

4 Answers4

3

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();
attofi
  • 288
  • 1
  • 6
1

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.

Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

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.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
0

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();
Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28