The number of seconds in "HH: MM: SS"

What is the best way to get the number of seconds in a string representation such as "hh: mm: ss"?

Obviously, Integer.parseInt (s.substring (...)) * 3600 + Integer.parseInt (s.substring (...)) * 60 + Integer.parseInt (s.substring (...)) works.

But I do not want to check this and reinvent wheal, I expect that there is a way to use DateTimeFormat or other classes from standard libraries.

Thanks!

+4
source share
4 answers

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 used to compensate for different time zones, and there is no problem with daylight saving time, because SimpleDateFormat does NOT use the actual date, it returns the Epoc date (January 1, 1970 = no DST).

Simplification (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 look at Joda-Time ...

+9
source

Original method: Calendar version (updated with 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 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 did it by heart just by looking at the documentation, so there may be a typo or two.

+3
source

joda-time - 1 option. infact I prefer this library for all date manipulations. I went through java 5 javadoc and found this enum class which is simple and useful for you. java.util.concurrent.TimeUnit. look at the conversion methods (...). http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/concurrent/TimeUnit.html

+1
source

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


All Articles