Java 8
So, start with How to parse/format dates with LocalDateTime? (Java 8) and DateTimeFormatter
you can convert a String
value to a LocalDateTime
using something like...
String value = "20040805034000";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime ldt = LocalDateTime.parse(value, format);
System.out.println(ldt);
Which outputs 2004-08-5T03:40
.
Next you can use ChronoUnit.SECONDS.between
to calculate the number of seconds between two times, but this means you need an anchor time, which would be midnight in your case...
LocalDateTime midnight = ldt.withHour(0).withMinute(0).withSecond(0).withNano(0);
long seconds = ChronoUnit.SECONDS.between(midnight, ldt);
System.out.println(seconds);
Which outputs 13200
If you can't use Java 8, then use Joda-Time instead. So starting with Converting a date string to a DateTime object using Joda Time library and Java (Joda): Seconds from midnight of LocalDateTime
String value = "20040805034000";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMddHHmmss");
LocalDateTime dt = formatter.parseLocalDateTime(value);
System.out.println(dt);
LocalDateTime midnight = dt.withMillisOfDay(0);
long seconds = Seconds.secondsBetween(midnight, dt).getSeconds();
System.out.println(seconds);