【问题标题】:how to get year month day from long date? [closed]如何从长日期获取年月日? [关闭]
【发布时间】:2020-03-06 12:22:39
【问题描述】:

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

    long date = a.creationDate;

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

【问题讨论】:

  • 与发布方式完全相同(尽管 API 很旧),假设 a.creationDate 是自 UTC 1970 年 1 月 1 日午夜以来的毫秒数(如 System.currentTimeMillis() 返回的那样)
  • 不要再使用SimpleDateFormat。使用现代的java.time.format.DateTimeFormatter
  • 你的代码有什么问题?
  • 展示你尝试过的东西总是有益的
  • 你知道java.time吗?

标签: java android


【解决方案1】:

如果您想从以毫秒为单位的日期时间中提取年、月和日的单个值,您现在应该使用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 级别,很遗憾,您必须导入 backport library,阅读 this 以获取说明...

【讨论】:

  • 感谢它的工作。但是你能帮助降低api吗?这项工作适用于 26 岁及以上
  • @Mohammadkhors 是的,请参阅我编辑的答案。
猜你喜欢
  • 2022-12-11
  • 1970-01-01
  • 1970-01-01
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多