2

I have string "6:00 AM" i want to convert this string to seconds or milliseconds in java. Please suggest me standard way to convert this.

seconds from midnight "00:00 am"

Sameer Kazi
  • 17,129
  • 2
  • 34
  • 46

2 Answers2

11

Java 7

Convert the String to a Date...

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
TimeZone gmt = TimeZone.getTimeZone("GMT");
sdf.setTimeZone(gmt);
Date date = sdf.parse("6:00 am");

Because there is no date information, this will be the milliseconds since the epoch + your time.

Convert the Date to seconds

long seconds = date.getTime() / 1000;
System.out.println(seconds);

Which outputs 21600 seconds, 360 minutes or 6 hours

Java 8

Something more like...

LocalTime lt = LocalTime.parse("6:00 AM", 
                DateTimeFormatter.ofPattern("h:m a"));
System.out.println(lt.toSecondOfDay());

...for example...

JodaTime

LocalTime lt = LocalTime.parse("6:00 am", 
                new DateTimeFormatterBuilder().
                                appendHourOfDay(1).
                                appendLiteral(":").
                                appendMinuteOfHour(1).
                                appendLiteral(" ").
                                appendHalfdayOfDayText().toFormatter());
LocalTime midnight = LocalTime.MIDNIGHT;
Duration duration = new Duration(midnight.toDateTimeToday(), lt.toDateTimeToday());
System.out.println(duration.toStandardSeconds().getSeconds());
Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Great answer! **To future visitors:** The `java.util` Date-Time API and their formatting API, `SimpleDateFormat` are outdated and error-prone. It is recommended to stop using them completely and switch to the [modern Date-Time API](https://www.oracle.com/technical-resources/articles/java/jf14-Date-Time.html). Also, quoted below is a notice from the [home page of **Joda-Time**](https://www.joda.org/joda-time/): *Note that from Java SE 8 onwards, users are asked to migrate to `java.time` (JSR-310) - a core part of the JDK which replaces this project.* – Arvind Kumar Avinash Dec 30 '22 at 13:07
1

Joda-time is a good choice when you need to deal with date time calculation.

import org.joda.time.*;
import org.joda.time.format.*;

DateTimeFormatter fmt = DateTimeFormat.forPattern("K:mm a");
DateTime end = fmt.parseDateTime("6:00 AM");
DateTime start = fmt.parseDateTime("00:00 AM");
Interval interval = new Interval(start,end);
long millSec = interval.toDurationMillis();
long second = interval.toDuration().getStandardSeconds();
Dongqing
  • 674
  • 1
  • 5
  • 19
  • What version of Joda-Time are you using? I tried using 2.4 and 2.7 but both give me an error for `Interval interval = new Interval(start,end);` – MadProgrammer Jan 15 '15 at 05:53