【问题标题】:Android: Incorrect Date when Converting from SecondsAndroid:从秒转换时的日期不正确
【发布时间】:2013-05-21 18:23:47
【问题描述】:

我正在将 XML 字符串中的一些日期数据解析为模型对象的层次结构。日期采用 10 位秒格式。我使用下面的方法将这些秒转换为 Date 对象

public static Date getDateFromSecondsString(String seconds){
    try{
        long millis = Long.parseLong(seconds) * 1000;
        Date date = new Date(millis);
        return date;
    }
    catch(Exception ex){
        ex.printStackTrace();
    }

    return null;
}

问题来了……

当我在运行时单步执行解析代码时(代码 sn-p 如下所示),日期转换方法正在返回预期日期。

Element startDateElt = eventElt.getChild("start_date");
if(startDateElt != null){
    startDateElt.setEndTextElementListener(new EndTextElementListener() {
        @Override
        public void end(String body) {
            currEvent.startDate = DateTimeUtil.getDateFromSecondsString(body);
        }
    });
}

但是,一旦我用解析的数据填充完我的模型对象,日期就会出错。以下是一些示例:

Seconds: 1369206000, should be: 2013-05-22, unfortunately is: 2013-05-03
Seconds: 1369292400, should be: 2013-05-23, unfortunately is: 2013-05-04
Seconds: 1369551600, should be: 2013-05-26, unfortunately is: 2013-04-30
Seconds: 1369638000, should be: 2013-05-27, unfortunately is: 2013-05-01
Seconds: 1369724400, should be: 2013-05-28, unfortunately is: 2013-05-02

我查看了我的代码,以确保在解析 XML 的时间和显示日期的时间之间没有修改日期。我知道 Java/Android 中的 Date 对象有些混乱,但它们会像这样吗?

任何建议或见解将不胜感激。

【问题讨论】:

  • 在设备上查看当前日期,是否正确?
  • DateTimeUtil 类从何而来?
  • @bwt:那堂课是我自己的。
  • 请在您将日期对象格式化为字符串的位置发布您的代码。
  • 代码似乎正确,请发布更多代码,并包括您记录文本的部分Seconds: xxxx, should be xxxx, ...

标签: java android date xml-parsing seconds


【解决方案1】:

事实证明,问题在于我在某些本应使用 Date.toDate 的地方使用了 Date.toDay() () 代替。呸!我不喜欢 Java 的 Date 实现。

感谢所有付出两分钱的人,谨以此作为对可能将 toDay() 混淆的任何人的警告toDate().

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2015-09-10
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多