我将向您展示三种方法(a)从长值中获取分钟字段,以及(b)使用所需的日期格式进行打印。一个使用java.util.Calendar,另一个使用Joda-Time,最后一个使用Java 8及更高版本中内置的java.time框架。
java.time框架取代了旧的捆绑日期时间类,并且受Joda-Time(由JSR 310定义,并由ThreeTen-Extra项目扩展)启发。
使用Java 8和更高版本时,可以使用java.time框架。否则,例如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 );
msSinceEpoch:1289375173771即时:2010-11-10T07:46:13.771Z输出:07:46:13:771