【问题标题】:Date format parsing in android from April 18 2016 10:41 AM to 04/18/2016 10:41从 2016 年 4 月 18 日上午 10:41 到 2016 年 4 月 18 日 10:41 在 android 中解析日期格式
【发布时间】:2016-04-18 04:49:59
【问题描述】:

我正在尝试将April 18 2016 10:41 AM 解析为04/18/2016 10:41。这是我的代码

private String dateFormat(String strCurrentDate) throws ParseException {

        SimpleDateFormat format = new SimpleDateFormat("mmmm dd yyyy hh:mm Z");
        Date newDate = null;
        newDate = format.parse(strCurrentDate);
        format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
        String date = format.format(newDate);
        Log.d("DATE_FORMATE_TESTING", date);
        return date;

    }

但它给出了以下错误

04-18 10:41:43.834 7526-7526/gps.clock.com W/System.err: java.text.ParseException: Unparseable date: "April 18 2016 01:41 PM" (at offset 0)
04-18 10:41:43.834 7526-7526/gps.clock.com W/System.err:     at java.text.DateFormat.parse(DateFormat.java:579)
04-18 10:41:43.834 7526-7526/gps.clock.com W/System.err:     at gps.clock.com.MainActivity.dateFormat(MainActivity.java:441)
04-18 10:41:43.834 7526-7526/gps.clock.com W/System.err:     at gps.clock.com.MainActivity.access$500(MainActivity.java:70)
04-18 10:41:43.834 7526-7526/gps.clock.com W/System.err:     at gps.clock.com.MainActivity$1$4.onClick(MainActivity.java:303)

谁能告诉我该如何解决?为什么显示Unparseable date。我应该如何解析它? 提前致谢。

【问题讨论】:

  • 你在用棉花糖吗?
  • 您在第一个模式中的月份有小写的ms。它们应该是大写的。上午/下午的字符是a,而不是Z。请参考SimpleDateFormat docs
  • @MikeM。我尝试使用 MMMM 而不是 mmmm。但我仍然遇到同样的错误。
  • 您是否也更改了Z

标签: android date parsing datetime


【解决方案1】:

试试下面的代码

    String strCurrentDate = "April 18 2016 10:41 AM";
    SimpleDateFormat format = new SimpleDateFormat("MMM dd yyyy hh:mm a");
    Date newDate = null;
    try {
        newDate = format.parse(strCurrentDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    format = new SimpleDateFormat("MM/dd/yyyy hh:mm");
    String date = format.format(newDate);
    System.out.print(date);

【讨论】:

  • 是的,这对我有用。我会接受这个答案。你能告诉我 SimpleDateFormate("MMM dd yyyy hh:mm a") 中的 a 和 Z 有什么区别吗?
  • 'a'用于表示上午或下午,其中'Z'(祖鲁时间)表示时区,因此无法解析。
【解决方案2】:

我认为您需要调整原始格式字符串。

SimpleDateFormat format = new SimpleDateFormat("mmmm dd yyyy hh:mm Z");

应该是

SimpleDateFormat format = new SimpleDateFormat("MMMM dd yyyy hh:mm a");

【讨论】:

    【解决方案3】:

    在java日期格式mM都有不同的含义。 m 用于解析分钟M 用于解析

    在您的示例中,您使用小写 m 解析月份,这会导致错误。正如@Mike M 所建议的那样。将您的ms 更改为大写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 2018-07-25
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多