Pergunta

I want to convert simple time format into millisecond. I have let say a time 3:14 and I want to convert it into millisecond. I have this following code but it gives me a negative value.

SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date d = format.parse("3:14");
long time = time.getTime();
Foi útil?

Solução

Explanation

My guess… You neglected to specify a time zone. So your JVM's default time zone was applied while parsing the string into a Date instance. A Date has a date and time portion. Without a date portion, the class assumed you meant the epoch, the first moment of 1970 UTC. I bet your default time zone was behind UTC by more than 3 hours. So when adjusted to your time zone, the result was a date-time in 1969. Such a date-time (occurring before the epoch) is represented with a negative number.

Lessons Learned

(A) Specify a time zone rather than rely on implicit default.

(B) Avoid the notoriously troublesome java.util.Date and .Calendar classes. Use the Joda-Time library.

(C) If you want to work with a time only, no date, the use the Joda-Time LocalTime class.

Outras dicas

To get the milliseconds since 1970-01-01 until the current date just use

System.currentTimeMillis();

If you want to get the milliseconds that have passed since midnight, then you have to obtain the time for midnight and substract that to the current time. Here is the full example.

// current time
Calendar today = Calendar.getInstance();

// Set the hour to midnight up to the millisecond
today.set(Calendar.HOUR_OF_DAY,0);
today.set(Calendar.MINUTE,0);
today.set(Calendar.SECOND,0);
today.set(Calendar.MILLISECOND,0);

// compute currenttime - midnight to obtain the milliseconds of today
long milliseconds = System.currentTimeMillis()-today.getTimeInMillis();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top