如何仅从时间为 23:59:59 的纪元时间获取日期

How do I get Date only from epoch time having time as 23:59:59

我有日期 2015-12-25 23:59:59 以纪元毫秒 1451087999000 的形式,我只想要日期部分,即 2015/12/25,我如何有效地做到这一点可能与JODA 时间库是当今处理 java 中日期时间的标准。

我有这段代码在大多数情况下都有效,但是当时间像 23:59:59 时,它会给我下一个日期(在我的情况下,它会给出 2015-12-26,输入为 2015-12- 2523:59:59)-

String dateInMilliSeconds = "1451087999000";
String dateInYYYYMMDDFormat = DateHelper.convertDateFormat(new Date(Long.valueOf(dateInMilliSeconds)),DateHelper.yyyy_MM_dd);

DateHelper.convertDateFormat() -

public static final String yyyy_MM_dd = "yyyy-MM-dd";
public static String convertDateFormat( Date date, String outputFormat )
{
    String returnDate = "";
    if( null != date )
    {
        SimpleDateFormat formatter = new SimpleDateFormat(outputFormat);
        returnDate = formatter.format(date);
    }
    return returnDate;
}

您可以使用 localDate 从 java 8

LocalDate date = Instant.ofEpochMilli(dateInMilliSeconds).atZone(ZoneId.of(timeZone)).toLocalDate();

时间戳 1451087999000 在 UTC 中是 2015-12-25 23:59:59。在您的代码中,当您使用 SimpleDateFormat 格式化时,您没有指定时区,因此它被格式化为您当地的时区。

与 Joda 时间:

String dateInMilliSeconds = "1451087999000";

LocalDate date = new LocalDate(Long.parseLong(dateInMilliSeconds), DateTimeZone.UTC);

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");

String result = formatter.print(date);

我想说明两点:

  1. 时区很重要。
  2. 跳过过时的 类 DateSimpleDateFormat.

我的建议是:

    String dateInMilliSeconds = "1451087999000";
    LocalDate date = Instant.ofEpochMilli(Long.parseLong(dateInMilliSeconds))
            .atOffset(ZoneOffset.UTC)
            .toLocalDate();
    System.out.println(date);

这会打印

2015-12-25

请注意,您可以免费获得所需的输出格式:LocalDate.toString() 生成它。如果您希望能够生成不同的输出格式,请使用 a DateTimeFormatter.

时区

您的毫秒值不仅仅等于 2015-12-25 23:59:59。在 UTC 中等于此日期和时间 ,因此您需要确保您的转换使用此时区偏移量。当我 运行 你的代码在我的电脑上时,我错误地得到 2015-12-26 因为我的电脑在 Europe/Copenhagen 时区。

JSR-310 又名 java.time

Joda-Time 是公认的比 Java 1 中原始日期和时间 API 更好的替代品,许多人认为它很差而且很麻烦。 Joda-Time 项目现已完成,因为被称为 JSR-310 或 java.time 的现代 Java 日期和时间 API 已于三年半前问世,因此他们建议我们使用此反而。所以我的代码可以。