字符串到 java.sql.Date

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18438587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:37:59  来源:igfitidea点击:

String to java.sql.Date

javasqleclipsedatederby

提问by Tajha

I realize this has been asked a lot. I did actually look. I've spent hours looking around and trying to figure this out. I'm supposed to be making a program that stores what amounts to a list of appointments in a database, with a description, date, start time, and end time. It has to take input from the user to add or cancel appointments, so as far as I know that means I need to convert a string to a date.

我意识到这已经被问了很多。我确实看过。我花了几个小时环顾四周并试图弄清楚这一点。我应该制作一个程序,在数据库中存储相当于约会列表的内容,包括描述、日期、开始时间和结束时间。它必须接受用户的输入才能添加或取消约会,因此据我所知,这意味着我需要将字符串转换为日期。

These are my imports: import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Time; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Scanner;

这些是我的导入: import java.io.File; 导入 java.io.IOException; 导入 java.sql.Connection; 导入 java.sql.Date; 导入 java.sql.PreparedStatement; 导入 java.sql.ResultSet; 导入 java.sql.ResultSetMetaData; 导入 java.sql.SQLException; 导入 java.sql.Time; 导入 java.text.DateFormat; 导入 java.text.ParseException; 导入 java.text.SimpleDateFormat; 导入 java.util.ArrayList; 导入 java.util.Scanner;

As you can see, no java.util.Date there. Here is the bit where I'm getting the error:

如您所见,那里没有 java.util.Date。这是我收到错误的地方:

private static java.sql.Date getDay()
{
    Scanner in = new Scanner(System.in);
    String input;
    Date apptDay = null;
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    java.sql.Date sqlDate;
    System.out.println("\nPlease enter the date of the appointment, format: yyyy/mm/dd");
    while(apptDay == null)
    {
        try
        {
            input = in.next();
            apptDay = (Date) df.parse(input);
        }
        catch(ParseException e)
        {
            System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
        }
    }
    sqlDate = new Date(apptDay.getTime());
    return sqlDate;
}

I've added java.sql.Dates to it and mucked about with it a bunch trying to get it to work, but it's still giving me this:

我已经向它添加了 java.sql.Dates 并试图让它工作,但它仍然给我这个:

Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date at Calendar.getDay(Calendar.java:47)

Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date at Calendar.getDay(Calendar.java:47)

Any ideas on what I'm doing wrong or how to make this work would be very much appreciated.

任何关于我做错了什么或如何使这项工作的想法都将不胜感激。

Edit: I thought perhaps it would help if I added the bit of code that is calling this so maybe it will be more clear how I am trying to use it, so here is the addAppointment() method, so you can see where getDay() is being called and where it's going.

编辑:我想如果我添加了调用它的代码可能会有所帮助,所以也许它会更清楚我如何尝试使用它,所以这里是 addAppointment() 方法,所以你可以看到 getDay( ) 正在被调用以及它要去哪里。

public static void addAppointment() throws SQLException
{
    //get the info
    String desc = getDesc();
    java.sql.Date apptDay = getDay();
    Time[] times = getTime();
    Time startTime = times[0];
    Time endTime = times[1];
    int key;

    Connection conn = SimpleDataSource.getConnection(); //connect to the database

    try
    {
        PreparedStatement max = conn.prepareStatement("SELECT MAX(ID) FROM Calendar");
        ResultSet result = max.executeQuery();
        key = result.getInt("ID") + 1; 
        PreparedStatement stat = conn.prepareStatement(
                "INSERT INTO Calendar " +
                "VALUES (?, ?, ?, ?, ?)"); 
        stat.setInt(1, key);
        stat.setString(2, desc); 
        stat.setDate(3, apptDay);
        stat.setTime(4, startTime);
        stat.setTime(5, endTime);
        stat.execute();
        System.out.println("\nAppointment added!\n");
    }
    finally
    {
        conn.close(); //finished with the database
    }
}

采纳答案by Evgeniy Dorofeev

It would be much simpler to change the input format to yyyy-MM-ddand use java.sql.Date.valueOf(String date)method which converts a string in the above format to a java.sql.Date value directly.

将输入格式更改为yyyy-MM-dd并使用java.sql.Date.valueOf(String date)将上述格式的字符串直接转换为 java.sql.Date 值的方法会简单得多。

回答by rocketboy

java.sql.Dateand java.util.Dateare two different Classes. You need to convert the sql date into util date which is compatible with Calendar.

java.sql.Date并且java.util.Date是两个不同的类。您需要将 sql 日期转换为与 Calendar 兼容的 util 日期。

  Date jDate =  new Date(sqlDate.getTime());

and vice-versa

反之亦然

  java.sql.Date sqlDate =  new java.sql.Date(jDate.getTime());

回答by Maurice Perry

   sqlDate = new java.sql.Date(apptDay.getTime());

回答by Jainendra

This should work:

这应该有效:

private static java.sql.Date getDay()
{
    Scanner in = new Scanner(System.in);
    String input;
    Date apptDay = null;
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    java.sql.Date sqlDate;
    System.out.println("\nPlease enter the date of the appointment, format: yyyy/mm/dd");
    while(apptDay == null)
    {
        try
        {
            input = in.next();
            apptDay = (Date) df.parse(input);
        }
        catch(ParseException e)
        {
            System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
        }
    }
    sqlDate = new java.sql.Date(apptDay.getTime());
    return sqlDate;
}

回答by wxl24life

The following statement caused the error:

以下语句导致错误:

apptDay = (java.sql.Date) df.parse(input);

In fact, the type of the return value of java.text.DateFormat.parse(String)is java.util.Date, which is incomparable with java.sql.Date.

实际上, 的返回值的类型java.text.DateFormat.parse(String)java.util.Date,是 不可比的java.sql.Date

In your situation, the easiest way might be using java.util.Dateinstead of java.sql.Date.

在您的情况下,最简单的方法可能是使用java.util.Date而不是java.sql.Date.

Another note: your class name Calendaris duplicate with java.util.Calendar. And it is not a good coding style to use class names which are already used by the standard library.

另一个注意事项:您的班级名称Calendarjava.util.Calendar. 使用标准库已经使用的类名并不是一种好的编码风格。

回答by Eun Chong Lim

Date.valueOf(scanner.nextLine())

回答by Eun Chong Lim

String strDate = scanner.nextLine();

SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = format.parse(strDate);

回答by Pesilo Entertaiments Group

Try below method -

试试下面的方法 -

private static java.sql.Date getDay() throws SQLException {
    Scanner in = new Scanner(System.in);
    String input;
    java.util.Date utilDay = null;
    DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
    System.out.println("\nPlease enter the date of the appointment, format: yyyy-mm-dd");
    while(utilDay == null){
        try{
            input = in.next();
            utilDay = (java.util.Date) df.parse(input);
        }catch(ParseException e){
            System.out.println("Please enter a valid date! Format is yyyy/mm/dd");
        }
   }

   java.sql.Date sqlDate = new java.sql.Date(utilDay.getTime());
   return sqlDate;
}

And from main()method, call this method -

main()方法,调用这个方法 -

Date birthday = getDay();

回答by Ole V.V.

java.time

时间

It's time someone writes the modern answer to this question.

是时候有人写下这个问题的现代答案了。

Assuming that you are using (or can start using) a JDBC 4.2 compliant driver you should not use the two Dateclasses nor DateFormator SimpleDateFormat. All those classes are poorly designed, the last two particularly troublesome. They are also long outdated. Instead rely on java.time, the modern Java date and time API. It's much nicer to work with. We need a LocalDateand a DateTimeFormatter.

假设您正在使用(或可以开始使用)符合 JDBC 4.2 的驱动程序,则不应使用这两个DateDateFormatSimpleDateFormat。所有这些类都设计得很差,最后两个特别麻烦。它们也早已过时。而是依赖 java.time,现代 Java 日期和时间 API。和它一起工作要好得多。我们需要 aLocalDate和 a DateTimeFormatter

Now we're at it, don't use java.sql.Timeeither. Use LocalTimefrom java.time.

现在我们正在使用它,也不要使用java.sql.TimeLocalTime从 java.time使用。

So your variable declarations become:

所以你的变量声明变成了:

    //get the info
    String desc = getDesc();
    LocalDate apptDay = getDay();
    LocalTime[] times = getTime();
    LocalTime startTime = times[0];
    LocalTime endTime = times[1];
    int key;

Only for passing the java.time objects to your prepared statement you don't use setDateand setTime. You need to use setObject:

仅用于将 java.time 对象传递给您不使用setDate和的准备好的语句setTime。你需要使用setObject

        stat.setInt(1, key);
        stat.setString(2, desc); 
        stat.setObject(3, apptDay);
        stat.setObject(4, startTime);
        stat.setObject(5, endTime);
        stat.execute();

Everything else is as before. For parsing the user input string to a LocalDate, here is a short demonstration:

其他一切都和以前一样。为了将用户输入字符串解析为 a LocalDate,这里有一个简短的演示:

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/M/d");
    String input = "2019/11/09";
    try {
        LocalDate aptDate = LocalDate.parse(input, dateFormatter);
        System.out.println("Parsed date: " + aptDate);
    } catch (DateTimeParseException dtpe) {
        System.out.println("Please enter a valid date. Format is yyyy/mm/dd");
    }

The output from the last snippet is:

最后一个片段的输出是:

Parsed date: 2019-11-09

解析日期:2019-11-09

I have specified just one Mand one din the format pattern string to allow the user to enter one or two digits for month and day of month, for example 2019/11/9. Most users I know will appreciate this.

我在格式模式字符串中只指定了 1M和 1 d,以允许用户输入一或两位数字表示月份和月份的日期,例如2019/11/9。我认识的大多数用户都会欣赏这一点。

Link

关联