【问题标题】:Can't with String to Date convert不能用字符串到日期转换
【发布时间】:2013-11-05 12:57:32
【问题描述】:

我的字符串看起来像:Sun, 27-Oct-2013 11:31:31 GMT 为了让它更简单,我这样做:

if (s.length() > 10)
   s = s.substring(5, s.length() - 4);

之后

s = " 27-Oct-2013 11:31:31"

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date timestamp = null;

 try {
   timestamp = formatter.parse(s.trim());
 } catch (ParseException e) {
   e.printStackTrace();
 }

捕获异常java.text.ParseException: Unparseable date: "27-Oct-2013 11:31:31"

【问题讨论】:

  • 您应该尽量简化查找错误的过程 - 尝试仅使用字符串 27-Oct-2013 和格式 dd-MMMM-yyyy 和时间部分相同
  • 我试过你的代码,没有发生错误
  • 对我来说也一样 - 没有抛出异常
  • 对我来说也一样-根本不会抛出异常。没有 Locale.US 用法

标签: java android string date


【解决方案1】:

您应该为格式化程序指定月份用英文拼写的语言环境,否则它将使用您的默认语言环境。

SimpleDateFormat(String pattern)

使用指定的非本地化构造一个新的SimpleDateFormat 模式和DateFormatSymbolsCalendar为用户默认 语言环境。

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss", Locale.US);

【讨论】:

  • +1。并且鉴于字符串的时区是 GMT,时区也应该在 SimpleDateFormat 上设置为 GMT。
猜你喜欢
  • 2014-04-30
  • 2018-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多