有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在Android中更改日期格式

我是Android和Java开发的新手

我有这一天的类型"Fri Jan 27 00:00:00 GMT+00:00 1995"<;——(输入)

我想得到"1995/27/01"<;-(产出)

我使用的代码是:

String inputPattern = "EEE MMM dd HH:mm:ss z yyyy";
String outputPattern = "yyyy-MM-dd";

SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);

Date date = inputFormat.parse("Fri Jan 27 00:00:00 GMT+00:00 1995");
String str = outputFormat.format(date);

但我得到了一个ParseException

知道为什么吗


共 (2) 个答案

  1. # 1 楼答案

    如果使用java.time(可从Java 8获得),可以这样做:

    public static void main(String[] args) {
        // example input String
        String datetime = "Fri Jan 27 00:00:00 GMT+00:00 1995";
        // define a pattern that parses the format of the input String
        String inputPattern = "EEE MMM dd HH:mm:ss O uuuu";
        // define a formatter that uses this pattern for parsing the input
        DateTimeFormatter parser = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
        // use the formatter in order to parse a zone-aware object
        ZonedDateTime zdt = ZonedDateTime.parse(datetime, parser);
        // then output it in the built-in ISO format once,
        System.out.println("date, time and zone (ISO):\t"
                            + zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
        // then extract the date part
        LocalDate dateOnly = zdt.toLocalDate();
        // and output that date part using a formatter with a date-only pattern
        System.out.println("date only as desired:\t\t"
                            + dateOnly.format(DateTimeFormatter.ofPattern("uuuu/dd/MM")));
    }
    

    这段代码的输出是

    date, time and zone (ISO):  1995-01-27T00:00:00Z
    date only as desired:       1995/27/01
    
  2. # 2 楼答案

    可能会在代码中添加applyPattern函数

    String inputPattern = "EEE MMM dd HH:mm:ss z yyyy";
    String outputPattern = "yyyy-MM-dd";
    
    SimpleDateFormat sdf = new SimpleDateFormat(inputPattern);
    Date date = sdf.parse("Fri Jan 27 00:00:00 GMT+00:00 1995");
    
    sdf.applyPattern(outputPattern);
    String str = sdf.format(date);