Date.getTime() 前一天返回

Date.getTime() is returning the previous day

我正在解析 dd-MM-yyyy 格式的日期并以秒为单位返回(除以 1000)。当我将它转换为 Unix 时间戳时,问题就来了,因为它将这一秒转换为前一天。我将用我的代码和示例进行解释:

private fun String.toTimestamp(): String {
    val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
    return (dateFormat.parse(this).time / 1000).toString
}

如果日期是 01/02/2019(2019 年 2 月 2 日),此方法 returns 1548975600。如果将它转换为日期(我使用的是 this 页面),它会 returns 01/31/2019 @ 11:00pm (UTC)。我试过添加小时、分钟和秒,甚至添加时区,但总是 returns 前一天。

另一个例子: 13-02-2019 > 1550012400 > 02/12/2019 @ 11:00pm (UTC)

日期来自 DatePicker,但如果我用下一种方式创建它 returns 正确的日期:

(Date().time / 1000).toString()

我已经尝试使用西班牙语和英语的系统语言,并将 Locale 更改为 Locale.ENGLISHLocale("es", "ES"),结果是一样的。

有什么建议吗?

//convert seconds to date try below function
public static String convertSecondsToDate(Long date) {
    try {
        long dateInMiliseconds = date *1000;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(dateInMiliseconds);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
        return simpleDateFormat.format(calendar.getTime());
    } catch (Exception e) {
        return "";
    }
}

java.time 和 ThreeTenABP

在Java语法中:

private static final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern("dd-MM-uuuu");

public static final String toTimestamp(String dateString) {
    long epochSecond = LocalDate.parse(dateString, dateFormatter)
            .atStartOfDay(ZoneOffset.UTC)
            .toEpochSecond();
    return String.valueOf(epochSecond);
}

让我们试试看:

    System.out.println(toTimestamp("13-02-2019"));

1550016000

在您链接到的 Epoch Unix 时间戳转换器 上检查此值:

02/13/2019 @ 12:00am (UTC)

SimpleDateFormat 是出了名的麻烦,而且 Date 早已过时。相反,我使用 java.time,现代 Java 日期和时间 API。这迫使我们明确给出时区或偏移量。在这种情况下作为预定义常量 ZoneOffset.UTC。这反过来又确保我们得到正确的结果,从而解决您的问题。另一个小优点是它给了我们 seconds 自纪元以来,所以我们不需要看起来很有趣的除以 1000.

我使用的进口商品是:

import org.threeten.bp.LocalDate;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeFormatter;

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在新旧 Android 设备上都能很好地工作。它只需要至少 Java 6.

  • 在 Java 8 及更高版本和较新的 Android 设备(从 API 级别 26)中,现代 API 是内置的。在这种情况下,从 java.time 包(而不是 org.threeten.bp)导入。
  • 在 Java 6 和 7 中获取现代 类 的 ThreeTen Backport(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。并确保使用子包从 org.threeten.bp 导入日期和时间 类。

链接