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
  • 16,423
  • 2
  • 32
  • 46

2 Answers2

10

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
  • 336,120
  • 22
  • 219
  • 344
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
  • 654
  • 1
  • 4
  • 17
  • 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