【问题标题】:Android date to string conversion issueAndroid日期到字符串转换问题
【发布时间】:2016-04-07 05:42:52
【问题描述】:

我想转换:星期三 4 月 6 日 09:37:00 GMT+03:00 2016 到 02/02/2012。 我尝试了什么

    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    Date date = sdf.parse(mydate);

 String mydate =  "Wed Apr 06 09:37:00 GMT+03:00 2016";
            SimpleDateFormat src = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");
            SimpleDateFormat dest = new SimpleDateFormat("dd/MM/yyyy");
            Date date = null;
            try {
                date = src.parse(mydate);
            } catch (ParseException e) {
                Log.d("deneme",e.getMessage());
            }
            String result = dest.format(date);

但它给出错误不可解析的日期:“Wed Apr 06 09:37:00 GMT+03:00 2016”(偏移量 0)知道如何解析它吗?

【问题讨论】:

标签: android string parsing datetime-format


【解决方案1】:

我认为您正在尝试格式化英语区域设置日期,但您的系统区域设置不是英语。因此,当您创建 SimpleDateFormat 对象时,请明确指定 Locale

试试这个代码,

    String mydate = "Wed Apr 06 09:37:00 GMT+03:00 2016";
    SimpleDateFormat src = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.ENGLISH);
    SimpleDateFormat dest = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
    Date date = null;
    try {
        date = src.parse(mydate);
    } catch (ParseException e) {
        Log.d("Exception",e.getMessage());
    }
    String result = dest.format(date);
    Log.d("result", result);

【讨论】:

  • 对于未来的访问者:旧的日期时间 API(java.util 日期时间类型及其格式类型,SimpleDateFormat)已过时且容易出错。建议完全停止使用它并切换到java.timemodern date-time API。使用thisthis 的答案,应该可以使用java.time API 解决它。
猜你喜欢
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
  • 2010-10-19
  • 2013-08-21
  • 2012-06-24
相关资源
最近更新 更多