【问题标题】:Illegal argument exception in formatting Calendar object格式化日历对象中的非法参数异常
【发布时间】:2023-03-28 05:50:01
【问题描述】:

我有一个日历对象,我想以这种格式显示它:“year.month.day hour.min.sec TimeZone”

我编写了以下代码行,但最后一行抛出 IllegalArgumentException。

我不知道我的问题在哪里。任何建议将不胜感激。谢谢。

Calendar date = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss Z");
String bookingDate = formatter.format(date);

===========

更新

===========

日志:

> 09-30 11:19:47.205: E/AndroidRuntime(19285): FATAL EXCEPTION: main
> 09-30 11:19:47.205: E/AndroidRuntime(19285): Process:
> com.passenger, PID: 19285 09-30 11:19:47.205:
> E/AndroidRuntime(19285): java.lang.IllegalArgumentException: Bad
> class: class java.util.GregorianCalendar 09-30 11:19:47.205:
> E/AndroidRuntime(19285):  at
> java.text.DateFormat.format(DateFormat.java:296) 09-30 11:19:47.205:
> E/AndroidRuntime(19285):  at java.text.Format.format(Format.java:93)
> 09-30 11:19:47.205: E/AndroidRuntime(19285):  at
> com.fragment.bookingdetail.BookingDetailFragment.sendDataToAP(BookingDetailFragment.java:1105)
> 09-30 11:19:47.205: E/AndroidRuntime(19285):  at
> com.fragment.bookingdetail.BookingDetailFragment.sendBookingToServer(BookingDetailFragment.java:782)
> 09-30 11:19:47.205: E/AndroidRuntime(19285):  at
> com.fragment.bookingdetail.BookingDetailFragment.onClick(BookingDetailFragment.java:340)

【问题讨论】:

  • 发布异常消息和堆栈跟踪。
  • 尝试将 Z 包装为 'Z'
  • 注意:SimpleDateFormat 构造函数采用第二个参数 Locale。 SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss Z", Locale.ENGLISH);
  • @SotiriosDelimanolis,由于我提到了发生异常的位置和位置,因此日志可能没有用。无论如何,我更新了我的问题。谢谢。
  • @getlost,抱歉没用 :(

标签: java android calendar simpledateformat


【解决方案1】:

基本上你不能用DateFormat 格式化Calendar 对象。使用Calendar#getTime() 并将生成的Date 对象传递给format 调用。

【讨论】:

    【解决方案2】:

    试试这个

    Calendar date = Calendar.getInstance(TimeZone.getDefault());
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss Z", Locale.ENGLISH);
    String bookingDate = formatter.format(date.getTime());
    System.out.println(bookingDate); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多