有 Java 编程相关的问题?

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

字符串中的java日期到日期转换中的日期

我的日期是String格式的"2019-10-30 12:17:47"。我想将其与时间一起转换为Date的实例,以便比较两个日期对象

这就是我尝试过的:

String dateString = "2019-10-30 12:17:47"        //Date in String format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  HH-mm-ss");    //sdf
Date d1 = format.parse(dateString);

但在这里,我得到的异常是“无法解析的日期异常”

请帮忙


共 (4) 个答案

  1. # 1 楼答案

    要格式化的字符串中的日期与格式化程序不匹配。请参阅此处的更多详细信息, https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html

    @Test
    public void test2() {
        String dateString = "2019-10-30 12:17:47";        //Date in String format
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    //sdf
        try {
            Date d1 = format.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
  2. # 2 楼答案

    你的代码出了什么问题

    在格式模式字符串yyyy-MM-dd HH-mm-ss中,日期和时间之间有两个空格。由于日期字符串2019-10-30 12:17:47只有一个空格,因此格式化程序通过抛出异常来处理对象。这也是蒂姆·比格莱森在评论中所说的。deHaar的评论也是正确的:小时、分钟和秒之间的连字符与日期字符串中的冒号也不匹配

    该怎么办

    the good answer by deHaar

  3. # 3 楼答案

    有两种方法

    首先是你的方式

        String dateString = "2019-10-30 12:17:47"; // Date in String format
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // sdf
        Date d1 = format.parse(dateString
    

    二是我的方式(当地日期)

        LocalDate resultDate = dateFormat("2019-10-30 12:17:47");
        System.out.println(resultDate);
    
      public static LocalDate dateFormat(String textTypeDateTime) {
    
        final DateTimeFormatter dateTimetextFormatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDate.parse(textTypeDateTime, dateTimetextFormatter);
      }
    
  4. # 4 楼答案

    你真的应该切换到java.time(正如你问题下面的一条评论中所建议的那样)。它并不比java.util中过时的时态类更难,但在偏移量、时区、夏令时和世界上众多不同的日历方面更不容易出错,功能更强大

    看看这个小例子:

    public static void main(String[] args) {
        String dateString = "2019-10-30 12:17:47";
        // define your pattern, should match the one of the String ;-)
        String datePattern = "yyyy-MM-dd HH:mm:ss";
    
        // parse the datetime using the pattern
        LocalDateTime ldt = LocalDateTime.parse(dateString,
                                                DateTimeFormatter.ofPattern(datePattern));
    
        // print it using a different (here a built-in) formatting pattern
        System.out.println(ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        // or you just use the one defined by you
        System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePattern)));
        // or you define another one for the output
        System.out.println(ldt.format(DateTimeFormatter.ofPattern("MMM dd yyyy HH-mm-ss")));
    }
    

    我的系统上的输出如下所示:

    2019-10-30T12:17:47
    2019-10-30 12:17:47
    Okt 30 2019 12-17-47