Joda使用正确的DateTimeZone解析24小时时间模式

时间:2019-01-14 15:21:36

标签: jodatime android-jodatime

再一次我在时间戳,日期等方面苦苦挣扎。

我有以下课程:

RELEASE

我通过参数呼叫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 = “ 16:03
  • timeString24h = 1547222580 (格林尼治标准时间2019年1月11日星期五16:03:00)

返回:

  

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

对于打给dateUTCseconds的电话,我正在使用:

  • getDateTimeFromSeconds = 1547222580
  • timeSeconds

返回:

  

2019-01-11T16:03:00.000Z


我该怎么办,那两个DateTime对象恰好代表同一时间?

编辑: 我的怀疑是,我必须在这里做些事情:

dateTimeZone = DateTimeZone.UTC

1 个答案:

答案 0 :(得分: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;
    }