如何从长日期获取年月日?

时间:2020-03-06 12:22:39

标签: java android

如何从长日期中以“ dd / MM / yyyy”格式提取年月日。

    long date = a.creationDate;

    SimpleDateFormat dateFormatNew = new SimpleDateFormat("dd/MM/yyyy");
    String formattedDate = dateFormatNew.format(date);

1 个答案:

答案 0 :(得分:0)

如果要从以毫秒为单位的日期时间中提取年,月和日的单个值,则现在应该使用java.time
参见以下示例:

public static void main(String[] args) {
    // example millis of "now"
    long millis = Instant.now().toEpochMilli(); // use your a.creationDate; here instead
    // create an Instant from the given milliseconds
    Instant instant = Instant.ofEpochMilli(millis);
    // create a LocalDateTime from the Instant using the time zone of your system
    LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    // then print the single parts of that LocalDateTime
    System.out.println("Year: " + ldt.getYear()
        + ", Month: " + ldt.getMonthValue()
        + " (" + ldt.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH)
        + "), Day: " + ldt.getDayOfMonth()
        + " (" + ldt.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH)
        + ")");
}

输出是这样的:

Year: 2020, Month: 3 (March), Day: 6 (Friday)

如果您支持的Android API级别低于26,则很遗憾,您必须导入backport library,阅读this以获得说明...