I want to achieve a similar operation in java:
time = "2014-05-19 13:36:05" interval = "60 (seconds)" time - interval = "2014-05-19 13:35:05"
What’s the best approach to express this in Java
given the following constraints:
The datetime is a formated string.
The interval is an integer.
The calculated time should be also a datetime formatted string.
Advertisement
Answer
You should work with “Date” objects, which basically represent an instance in time (number of milliseconds since Unix epoch) when doing the subtraction. Once you have a “Date” Object you can use “getTime” method (http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime()) to get this milliseconds value, and subtract 60 seconds (make sure to work with milliseconds not seconds!), and create a new “Date” with that resulting value.
This is one approach. There are many, Joda library is also quite popular. It has a method to subtract milliseconds from its date representation, http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#minusSeconds(int).