4

I have a Timestamp being passed from an external source to my application in the 2011-01-23-12.31.45 format. I need to compare it to the current system timestamp an make sure its less than 2 minutes difference. Any ideas on how to accomplish this?

c12
  • 9,557
  • 48
  • 157
  • 253

2 Answers2

5

That's a date, not a timestamp. You can parse it using java.text.SimpleDateFormat, using the yyyy-dd-MM-HH.mm.ss format:

SimpleDateFormat sdf = new SimpleDateFormat("yyy-dd-MM-HH.mm.ss");
Date date = sdf.parse(inputDateString);
long timestamp = date.getTime();

And then compare - a minute has 60 * 1000 millis.

Using joda-time for date-time operations is always preferred - it will:

  • have a thread-safe implementation of the dataformat - DateTimeFormat (the one above is not thread-safe)
  • simply do Minutes.minutesBetween(..) to find out the minutes between the two instants, rather than calculating.
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

Well this can be optimized but this is what I came up with. It needs some work but it should get you started.

public class Test {

private final String serverValue = "2011-01-23-12.31.45"; //Old should fail
private final String serverValueNew = "2011-03-28-14.02.00"; //New

private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss");


public boolean plusMinusTwoMins(String serverValue) {
    boolean withinRange = false;
    Date now = Calendar.getInstance().getTime();
    Date serverDate = now;

    try {
        serverDate = dateFormat.parse(serverValue);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    long millis = Math.abs(now.getTime() - serverDate.getTime());
    System.out.println("Millis: " + millis);

    //1000ms * 60s * 2m
    if (millis <= (1000 * 60 * 2)) {
        withinRange = true;
    }

    return withinRange;
}

public static void main(String[] args) {
    Test test = new Test();
    boolean value = test.plusMinusTwoMins(test.serverValue);
    System.out.println("Value: " + value);
    boolean value2 = test.plusMinusTwoMins(test.serverValueNew);
    System.out.println("Value2: " + value2);
}

}

blong824
  • 3,920
  • 14
  • 54
  • 75
  • be careful with static `SimpleDateFormat` - it's not threadsafe. – Bozho Mar 28 '11 at 21:11
  • Yea I wrote this pretty fast. Just trying to give an idea of one of the ways to accomplish this. I voted up your answer. Pretty much the same idea but with joda time for thread safety. – blong824 Mar 28 '11 at 21:13