String qtm = "00:02:00";
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
java.util.Date d = null;
try
{
d = formatter.parse(qtm);}
catch (java.text.ParseException e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println(d);
this code gives me:-
Thu Jan 01 00:02:00 IST 1970
in my program I want to keep a time quantum of 2 minutes for roundrobin algo, how can I do that?? please help me. when I give
long curr= d.getTime();
system.out.println(d);
it gives the output:-
-19500000
please tell me how to give just 2 minutes as an interval and to assign it to a variable....
The problem at the moment is that your SimpleDateFormat
is in your local time zone, whereas Date.getTime()
gives you the milliseconds since the Unix epoch in UTC.
You can fix this as:
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
... and then use getTime()
as before.
Ideally, it would be better to use Joda Time or the Java 8 java.time
package, both of which have a Duration
type to represent this sort of value. Joda Time has a PeriodFormatter
which could be used to parse this as a Period
and convert that into a Duration
, which is a bit long-winded, admittedly. I don't see a way of parsing straight to a Duration
for either of them...
See more on this question at Stackoverflow