0

我又一次在时间戳、日期等问题上苦苦挣扎。

我有以下课程:

public class TimeConverter {
    private static final String TAG = TimeConverter.class.getSimpleName();

    public static final String PATTERN_TIME_24H = "HH:mm";


    /**
     * Returns a DateTime object for a given string in format HH:mm, assuming that the day is TODAY in UTC.
     *
     * @param timeString24h  - The string representing the time in format HH:mm
     * @param dateUTCseconds - The UTC timestamp to get the correct date for the given timeString24h
     * @return DateTime object for the given time where actual date is derived from dateUTCseconds
     */
    public static DateTime getDateTimeFrom24hString(final String timeString24h, final long dateUTCseconds) {
        final LocalDate localDate = new LocalDate(dateUTCseconds * 1000, DateTimeZone.UTC);
        final DateTimeFormatter formatter = DateTimeFormat.forPattern(PATTERN_TIME_24H);
        DateTime dateTime = formatter.parseDateTime(timeString24h)
                .withDate(localDate);
        Log.d(TAG, "getDateTimeFrom24hString() --> input: " + timeString24h + ", output: " + dateTime.toString());
        return dateTime;
    }

    public static DateTime getDateTimeFromSeconds(final long timeSeconds, final DateTimeZone dateTimeZone) {
        final DateTime dateTime = new DateTime(timeSeconds * 1000, dateTimeZone);
        Log.d(TAG, "getDateTimeFromSeconds() --> input: " + timeSeconds + ", output: " + dateTime.toString());
        return dateTime;
    }

}

getDateTimeFrom24hString用参数打电话:

  • timeString24h= “16:03
  • dateUTCseconds= 1547222580(格林威治标准时间 2019 年 1 月 11 日星期五 16:03:00)

返回:

2019-01-11T16:03:00.000+01:00

对于getDateTimeFromSeconds我正在使用的电话:

  • timeSeconds= 1547222580
  • dateTimeZone = DateTimeZone.UTC

返回:

2019-01-11T16:03:00.000Z


我该怎么做,这两个 DateTime 对象完全代表相同的时间?

编辑: 我的怀疑是,我必须在这里做点什么:

final DateTimeFormatter formatter = DateTimeFormat.forPattern(PATTERN_TIME_24H);
        //TODO: Need to "tell" the dateTime object, that the parsed date is already UTC time
        DateTime dateTime = formatter.parseDateTime(timeString24h)
                .withDate(localDate);
4

1 回答 1

0

我刚刚找到了一个似乎可以解决问题的解决方案:

    public static DateTime getDateTimeFrom24hString(final String timeString24h, final long dateUTCseconds) {
        final LocalDate localDate = new LocalDate(dateUTCseconds * 1000, DateTimeZone.UTC);

        final DateTimeFormatter formatter = DateTimeFormat.forPattern(PATTERN_TIME_24H);
        DateTime dateTime = formatter.parseDateTime(timeString24h)
                .withDate(localDate);

        DateTime dateTimeUtc = new DateTime(DateTimeZone.UTC)
                .withDate(localDate)
                .withTime(dateTime.toLocalTime());

        return dateTimeUtc;
    }
于 2019-01-14T16:58:57.413 回答