配对时间()而不是结果

Joda Time toDate() wrong result

我正在使用此代码:

date - 来自 DatePicker 的日期对象,作为字符串 Thu Sep 10 00:00:00 GMT+03:00 2020

mDate = DateTime(date)
           .withHourOfDay(0)
           .withMinuteOfHour(0)
           .withSecondOfMinute(0)
           .withMillisOfSecond(0)
           .toDate()

结果 mDate - Wed Sep 09 03:00:00 GMT+03:00 2020

这有什么问题吗?

您没有将 DateTime 对象正确转换为 java.util.Date。正确的方法是从 DateTime 对象获取毫秒数并用毫秒数初始化 java.util.Date

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Define formatter
        DateTimeFormatter formatter = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss zZ yyyy");

        // Date-time string from DatePicker
        String strDateTime = "Thu Sep 10 00:00:00 GMT+03:00 2020";

        DateTime dateTime = DateTime.parse(strDateTime, formatter);
        System.out.println(dateTime);

        // No. of milliseconds from the epoch of 1970-01-01T00:00:00Z 
        long millis = dateTime.getMillis();
        System.out.println(millis);

        Date mDate = new Date(millis);
        // Display java.util.Date object in my default time-zone (BST)
        System.out.println(mDate);

        //Display java.util.Date in a different time-zone and using custom format
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+3"));
        System.out.println(sdf.format(mDate));
    }
}

输出:

2020-09-09T21:00:00.000Z
1599685200000
Wed Sep 09 22:00:00 BST 2020
Thu Sep 10 00:00:00 GMT+03:00 2020

注:java.util.Date不代表Date/Time对象。它只是代表没有。从 1970-01-01T00:00:00Z 纪元算起的毫秒数。它没有任何 time-zone 或 zone-offset 信息。当您打印它时,Java 打印通过应用您的 JVM 的 time-zone 获得的字符串。如果你想在其他时区打印它,你可以使用 SimpleDateFormat 来实现,如上所示。

我建议您从过时的 error-prone java.util date-time API 和 SimpleDateFormat 切换到 modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time. If your Android API level is still not compliant with Java8, check and Java 8+ APIs available through desugaring.

下面的table显示一个overview of modern date-time classes