首页 > 解决方案 > 如何从长日期获取年月日?

问题描述

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

    long date = a.creationDate;

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

标签: javaandroid

解决方案


如果您想从以毫秒为单位的日期时间中提取年、月和日的单个值,您现在应该使用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)

如果您支持低于 26 的 Android API 级别,不幸的是,您将不得不导入一个反向移植库,请阅读内容以获取说明...


推荐阅读