我想用给定的时区更改日期格式。我已经尝试使用SimpleDateFormat,但仍然失败了

时间:2017-06-13 07:03:03

标签: java android date date-format date-conversion

日期为Wed Jun 21 14:14:23 GMT+08:00 2017,我想将其转换为2017-06-21

这是我的代码:

String date = "Wed Jun 21 14:14:23 GMT+08:00 2017";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMMM dd HH:mm:ss 'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd");
Date d = null;
try {
    d = sdf.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
}

3 个答案:

答案 0 :(得分:1)

首先,我建议您停止使用旧的DateSimpleDateFormat类。它们已过时,full of bugs and design issues,并被新的日期/时间API取代。

如果您使用的是 Java 8 ,请考虑使用new java.time API

如果您使用的是 Java< = 7 ,则可以使用ThreeTen Backport,这是Java 8新日期/时间类的绝佳后端。对于 Android ,有ThreeTenABP(更多关于如何使用它here)。

以下代码适用于两者。 唯一的区别是包名称(在Java 8中为java.time,在ThreeTen Backport(或Android的ThreeTenABP)中为org.threeten.bp),但类和方法名称是相同的

要解析所需的String,只需创建DateTimeFormatter并将java.util.Locale设置为英语,以确保工作日和月份名称(在您的情况下为Wed }和Jun)被正确解析。如果未设置区域设置,将使用系统的默认值(如果默认值不是英语,则不起作用)。

String date = "Wed Jun 21 14:14:23 GMT+08:00 2017";
// create formatter (using English locale to make sure weekdays and month names are parsed correctly)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// parse local date
LocalDate dt = LocalDate.parse(date, fmt);
System.out.println(dt.toString()); // 2017-06-21

输出结果为:

  

2017年6月21日

答案 1 :(得分:0)

试试这个完美的作品

String  formatDate = "Wed Jun 21 14:14:23 GMT+08:00 2017";
        java.text.SimpleDateFormat dateTimeFormat = new java.text.SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy" , Locale.ENGLISH);
        java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);

        Date date = null;
        try {
            date = dateTimeFormat.parse(formatDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String format = dateFormat.format(date);

        Log.d("===========>>>>>",format);

答案 2 :(得分:0)

试试这个,它可以随心所欲地工作。

String input_date = "Wed Jun 21 14:14:23 GMT+08:00 2017";
SimpleDateFormat fromthis = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.ENGLISH);
SimpleDateFormat tothis = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date date = null;
try {
       date = fromthis.parse(input_date);
    } catch (ParseException e) {
       e.printStackTrace();
    }
String result = tothis.format(date);
System.out.println(result);

输入:Wed Jun 21 14:14:23 GMT + 08:00 2017

输出:2017-06-21

谢谢。

相关问题