【问题标题】:Getting Unparseable date exception while converting a timestamp string转换时间戳字符串时出现无法解析的日期异常
【发布时间】:2016-05-03 06:19:50
【问题描述】:

我正在尝试用 Java 中的时区字符串解析时间戳。我的字符串是:

"2013-01-01 15:30:00.2 +05:00"
"2003-01-01 02:59:04.123 -8:00"

这是我的解析代码:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
simpleDateFormat.parse("2013-01-01 15:30:00.2 +05:00");

但是,我在运行代码时收到此错误消息:

java.text.ParseException: Unparseable date: "2013-01-01 15:30:00.2 +05:00"

我也试过用下面的代码来解析它:

DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis();
DateTime dateTime = dateTimeFormatter.parseDateTime("2003-01-01 02:59:04.123 -8:00");
Timestamp timeStamp = new Timestamp(dateTime.getMillis());

这给了我一个例外:

Invalid format: "2003-01-01 02:59:04.123 -8:00" is malformed at " 02:59:04.123 -8:00"

我也尝试在日期之后的字符串中插入“T”,但它也给出了无效格式异常:

 Invalid format: "2003-01-01T02:59:04.123 -8:00" is malformed at " .123 -8:00"

这一定很简单——不过我不知道我哪里出错了。

感谢您的帮助!

【问题讨论】:

  • 注意ISODateTimeFormat.dateTimeNoMillis 的“no millis”部分 - 然后查看您要解析的值。
  • 我假设DateTimeFormatter 代码是 Joda Time,而不是 Java 8?如果您在帖子中指出这一点,将会很有用。
  • 有什么理由为什么你在 +05:00 有一个前导 0 而在 -8:00 没有?如果您对此格式有任何控制权,那么如果您可以使其更加一致,那将非常有帮助 - 理想情况下只需遵循 ISO-8601。
  • 嗯,基本上,您遇到了问题:“-8:00”与zZ 的预期时区格式不匹配。您无需输入 T - 您可以轻松地指定一个自定义格式来处理它 - 但如果您可以使用 -08:00 而不是 -8:00,您的生活会轻松得多。
  • 我以为你说你是从数据库中获取的?从根本上说,我强烈建议您尝试在尽可能接近其来源的地方修复不规则的格式。

标签: java timestamp-with-timezone


【解决方案1】:

你只是在 SimpleDateFormat(yyyy-MM-dd HH:mm:ss.SSS z) 中犯了一个错误, 其中 'z' 接受带有 General time zone 演示的 TimeZone。General time zone 接受:

GMTOffsetTimeZone:

GMT Sign Hours : Minutes
Sign: one of
         + -
 Hours:
         Digit
         Digit Digit
 Minutes:
         Digit Digit
 Digit: one of
         0 1 2 3 4 5 6 7 8 9

但你提到 +5:00 应该是 GMT+5:00。

还有 'Z''X' 代表 SimpleDateFormat 中的 TimeZone,分别接受 RFC 822 time zoneISO 8601 time zone

【讨论】:

    【解决方案2】:

    试试下面的代码:只需输入 GMT+5:30 而不是 +5:30

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class DateDemo {
    
        // main method
        public static void main(String[] args) {
    
            try {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
                Date d = simpleDateFormat.parse("2013-01-01 15:30:00.2 GMT+05:00");
                System.out.println(d);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多