如何在java中将"hh mm a"格式字符串转换为秒

Sam*_*azi 1 java datetime date-parsing

我有字符串"6:00 AM"我想在java中将此字符串转换为秒或毫秒.请建议我转换它的标准方法.

午夜时分"00:00 am"

Mad*_*mer 8

Java 7

转换StringDate......

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

因为没有日期信息,所以这将是自纪元+时间以来的毫秒数.

转换Date为秒

long seconds = date.getTime() / 1000;
System.out.println(seconds);
Run Code Online (Sandbox Code Playgroud)

其中输出21600秒,360分钟或6小时

Java 8

更像是......

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

...例如...

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());
Run Code Online (Sandbox Code Playgroud)