Java timestamp comparison

I have a timestamp transferred from an external source to my application in the format 2011-01-23-12.31.45. I need to compare it with the current timestamp of the system, make sure that the difference in it is less than 2 minutes. Any ideas on how to do this?

+4
source share
2 answers

This is a date, not a timestamp. You can java.text.SimpleDateFormat it using java.text.SimpleDateFormat using the format yyyy-dd-MM-HH.mm.ss :

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

And then compare - a minute of 60 * 1000 milliseconds.

Using joda-time for date and time operations is always preferable - it will be:

  • have a thread-safe implementation of dataformat - DateTimeFormat (the above is not thread-safe)
  • just do Minutes.minutesBetween(..) to find out the minutes between two moments, not to calculate.
+5
source

Well, this can be optimized, but this is what I came up with. It takes some work, but you need to get 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); } 

}

0
source

Source: https://habr.com/ru/post/1345617/


All Articles