我有字符串" 6:00 AM"我想在java中将此字符串转换为秒或毫秒。 请建议我转换它的标准方法。
从午夜起" 00:00"答案 0 :(得分:8)
将String
转换为Date
...
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
TimeZone gmt = TimeZone.getTimeZone("GMT");
sdf.setTimeZone(gmt);
Date date = sdf.parse("6:00 am");
因为没有日期信息,所以这将是自纪元+你的时间以来的毫秒数。
将Date
转换为秒
long seconds = date.getTime() / 1000;
System.out.println(seconds);
输出21600
秒,360分钟或6小时
更像是......
LocalTime lt = LocalTime.parse("6:00 AM",
DateTimeFormatter.ofPattern("h:m a"));
System.out.println(lt.toSecondOfDay());
...例如......
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());
答案 1 :(得分:1)
Joda-time是一个不错的选择。
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();