有 Java 编程相关的问题?

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

java中日期时间的日期转换

我的json的一个字段是String,它包含以下格式的时间:2017-04-04T20:22:33甚至2017-04-07T12:21:10.0355277+00:00。我的任务是把它转换成一个更简单的表达方式,比如:“Apr-4 20:22”。我在考虑创建一个SimpleDateFormat,但是它似乎不适合这种日期时间格式

有什么有效的方法来处理这项任务吗


共 (3) 个答案

  1. # 1 楼答案

    试试这个

     String date="2017-04-04T20:22:33";
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
     SimpleDateFormat sdf1 = new SimpleDateFormat("MMM-dd HH:mm");
     try{
        Date parseDate = sdf.parse(date);
        String output = sdf1.format(parseDate);
     }catch(Exception e) {
    
     }
    
  2. # 2 楼答案

    我觉得你把解析和格式搞混了:

    public String convert(String inputStr, String inputFormat, String outputFormat){
    
        Date date = new SimpleDateFormat(inputFormat).parse( inputStr );
        String outputStr = new SimpleDateFormat(outputFormat).format( date );
    
        return outputStr;
    }
    

    这样使用:

    convert("2017-04-04T20:22:33", "yyyy-MM-dd'T'HH:mm:ss", "d-MMM HH:mm");
    

    由于不需要字符串的无关部分,所以可以在传递到上述方法之前将其完全删除

  3. # 3 楼答案

    我有时会使用一种模式:

    private static final Pattern XSD_DATETIME_PATTERN = Pattern.compile(
            "([+-]?[0-9]{4})-(1[0-2]|0[1-9])-([0-9]{2})"
            + "[Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})(?:[.]([0-9]+))?"
            + "(?:([Zz])|([+-][0-9]{2}:[0-9]{2}))?");
    
    
    public static Date parseXsdDateTime(String s) {
        Matcher matcher = XSD_DATETIME_PATTERN.matcher(s);
        if (!matcher.matches()) {
            throw new IllegalArgumentException(
                    "Unparseable date: \"" + s + "\"");
        }
        // Determine timezone
        TimeZone tz;
        if (matcher.group(8) != null) {
            tz = TimeZone.getTimeZone("GMT");
        } else if (matcher.group(9) != null) {
            tz = TimeZone.getTimeZone("GMT" + matcher.group(9));
        } else {
            tz = TimeZone.getDefault();
        }
        Calendar cal = Calendar.getInstance(tz);
        cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(1)));
        cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(2))-1);
        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(3)));
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(4)));
        cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(5)));
        cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(6)));
        String millis = matcher.group(7);
        if (millis == null) {
            cal.set(Calendar.MILLISECOND, 0);
        } else {
            if (millis.length() > 3) {
                millis = millis.substring(0, 3);
            } else {
                while (millis.length() < 3) {
                    millis += "0";
                }
            }
            cal.set(Calendar.MILLISECOND, Integer.parseInt(millis));
        }
        return cal.getTime();
    }