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

时间:2019-10-30 06:57:38

标签: java date

我的日期是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 个答案:

答案 0 :(得分:3)

您的代码出了什么问题?

在格式模式字符串yyyy-MM-dd HH-mm-ss中,日期和时间之间有两个空格。由于您的日期字符串2019-10-30 12:17:47在那里只有一个空格,因此格式化程序通过抛出异常来对象。这也是Tim Biegeleisen在评论中说的。 deHaar的评论也是如此:小时,分钟和秒之间的连字符也不匹配日期字符串中的冒号。

该怎么办?

请参见the good answer by deHaar

答案 1 :(得分:2)

您应该真正切换到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

答案 2 :(得分: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();
    }
}

答案 3 :(得分:0)

有两种方法

首先是您的方式

    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);
  }
相关问题