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"
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"
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
Something more like...
LocalTime lt = LocalTime.parse("6:00 AM",
DateTimeFormatter.ofPattern("h:m a"));
System.out.println(lt.toSecondOfDay());
...for example...
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());
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();