What's the best way to get the number of seconds in a string representation like "hh:mm:ss"?
开发者_如何学编程Obviously Integer.parseInt(s.substring(...)) * 3600 + Integer.parseInt(s.substring(...)) * 60 + Integer.parseInt(s.substring(...)) works.
But I don't want to test that, and reinvent the wheal, I expect there is a way to use DateTimeFormat or other classes from standard libraries.
Thanks!
Based on pakores solution:
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date reference = dateFormat.parse("00:00:00");
Date date = dateFormat.parse(string);
long seconds = (date.getTime() - reference.getTime()) / 1000L;
reference
is used to compensate for different timezones and there is no problem with daylight saving time because SimpleDateFormat does NOT use the actual date, it return the Epoc date (January 1st, 1970 = no DST).
Simplifying (not much):
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dateFormat.parse("01:00:10");
long seconds = date.getTime() / 1000L;
but I would still have a look at Joda-Time...
An original way:
The Calendar
version (updated with the suggestions in the comments):
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dateFormat.parse(string);
//Here you can do manually date.getHours()*3600+date.getMinutes*60+date.getSeconds();
//It's deprecated to use Date class though.
//Here it goes an original way to do it.
Calendar time = new GregorianCalendar();
time.setTime(date);
time.setTimeZone(TimeZone.getTimeZone("UTC"));
time.set(Calendar.YEAR,1970); //Epoc year
time.set(Calendar.MONTH,Calendar.JANUARY); //Epoc month
time.set(Calendar.DAY_OF_MONTH,1); //Epoc day of month
long seconds = time.getTimeInMillis()/1000L;
Disclaimer: I've done it by heart, just looking at the documentation, so maybe there is a typo or two.
joda-time is 1 options. infact i prefer that library for all date manipulations. I was going thru the java 5 javadoc and found this enum class which is simple and useful for you. java.util.concurrent.TimeUnit. look at the convert(...) methods. http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/concurrent/TimeUnit.html
Here is the link to a Java example of time formatting.
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/i18n/format/simpleDateFormat.html
精彩评论