对于给定的Locale,Java simpleDateFormat不能正确解析日期?

时间:2016-07-20 08:47:09

标签: java android timezone simpledateformat

在我的代码中,我获取当前时间,然后根据" UTC"格式化它。时区,然后使用相同的时区解析它,因此将其转换为日期。问题是我得到的日期是#34; Wed Jul 20 13:04:51 GMT + 05:00 2016"比 它的格式化和解析如下面的代码

Calendar calendar = Calendar.getInstance();
    Date currentDate = calendar.getTime();
    //gives time as "Wed Jul 20 13:04:51 GMT+05:00 2016"

    dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    String dateText = dateFormat.format(currentDate);
    //This formats dates as following "Wed, 20 Jul 2016 08:04:51 +0000"

现在uptitil在这里工作正常,时区GMT + 05:00被转换为标准UTC,GMT + 00:00在格式化日期显示为+0000

 Date setteledDate = dateFormat.parse(dateText);

现在解析上述日期会给出以下日期。 "周三7月20日13:04:51 GMT + 05:00 2016"。问题是这个日期再次出现在GMT + 5中 我得到当前日期格式化它的整个目的,而不是解析它,因为目的是根据" UTC"来获取当前日期。 (GMT + 00:00)。

请帮忙。

1 个答案:

答案 0 :(得分:0)

以SimpleDateFormat格式将Z替换为z。

Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();

//gives time as "Wed Jul 20 13:04:51 GMT+05:00 2016"

SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

String dateText = dateFormat.format(currentDate);
Log.e("date",dateText);
//output Wed, 20 Jul 2016 09:01:20 UTC

dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
dateText = dateFormat.format(currentDate);
Log.e("date",dateText);
//output  Wed, 20 Jul 2016 09:02:04 GMT+00:00

//更新

SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        try {

            Date date = dateFormat.parse("Wed Jul 20 13:04:51 GMT+05:00 2016");
            Log.e("date",date.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }