我将向您展示三种方法来 (a) 从 long 值中获取分钟字段,以及 (b) 使用所需的日期格式打印它。一个使用java.util.Calendar,另一个使用Joda-Time,最后一个使用 Java 8 及更高版本中内置的 java.time 框架。
java.time 框架取代了旧的捆绑日期时间类,并受到 JSR 310 定义并由 ThreeTen-Extra 项目扩展的 Joda-Time 的启发。
java.time 框架是使用 Java 8 及更高版本时要走的路。否则,例如 Android,请使用 Joda-Time。java.util.Date/.Calendar 类是出了名的麻烦,应该避免。
java.util.Date & .Calendar
final long timestamp = new Date().getTime();
// with java.util.Date/Calendar api
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
// here's how to get the minutes
final int minutes = cal.get(Calendar.MINUTE);
// and here's how to get the String representation
final String timeString =
new SimpleDateFormat("HH:mm:ss:SSS").format(cal.getTime());
System.out.println(minutes);
System.out.println(timeString);
乔达时间
// with JodaTime 2.4
final DateTime dt = new DateTime(timestamp);
// here's how to get the minutes
final int minutes2 = dt.getMinuteOfHour();
// and here's how to get the String representation
final String timeString2 = dt.toString("HH:mm:ss:SSS");
System.out.println(minutes2);
System.out.println(timeString2);
输出:
24
09:24:10:254
24
09:24:10:254
java.time
long millisecondsSinceEpoch = 1289375173771L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , ZoneOffset.UTC );
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "HH:mm:ss:SSS" );
String output = formatter.format ( zdt );
System.out.println ( "millisecondsSinceEpoch: " + millisecondsSinceEpoch + " instant: " + instant + " output: " + output );
毫秒SinceEpoch:1289375173771 瞬间:2010-11-10T07:46:13.771Z 输出:07:46:13:771