简体   繁体   English

处理日期java.util,日期java.sql和SimpleDateFormat

[英]Handling dates java.util, dates java.sql and SimpleDateFormat

I have trouble at handling different formats of dates in a program. 我在处理程序中不同格式的日期时遇到麻烦。

As it it now, my query is executed, but i get dates from DB in a YYYY-MM-DD format. 现在,我的查询已执行,但是我从数据库以YYYY-MM-DD格式获取日期。 I want them in DD-MM-YYYY HH:mm format. 我希望它们采用DD-MM-YYYY HH:mm格式。

In a SQL file, dates are defined like this (in an INSERT INTO instruction) : 在SQL文件中,日期的定义如下(在INSERT INTO指令中):

to_date('2015/05/15 12:00', 'yyyy/mm/dd hh24:mi') 

In my java code, i try to make the user choose a date (Date object is a java.util.date) : 在我的Java代码中,我尝试使用户选择一个日期(Date对象为java.util.date):

DateFormat formater = new SimpleDateFormat("DD-MM-YYYY HH:mm", Locale.FRENCH);
String dateString;
dateString = sc.nextLine();
Date upperDate = formater.parse(dateString);
// a "lowerDate is also that way.

    List<Train> listTrains = new ArrayList<>();
            listTrains = manager.WhenTrain(departure_city, arrival_city, upperDate, lowerDate);

for(int i = 0; i<liste.size(); i++)
    {
        System.out.println(listTrains.get(i));
    }

In a method, i try to get values corresponding to various conditions, among them, dates, so i have : 在一种方法中,我尝试获取与各种条件相对应的值,其中包括日期,所以我有:

In the constructor and fields : 在构造函数和字段中:

    private PreparedStatement AllTrains;
    private PreparedStatement LookForDepartureStation;

    AllTrains = connection.prepareStatement("SELECT * FROM Trains"
                    + "WHERE departure = ? AND arrival = ? AND departurehour BETWEEN ? AND ?"); // Trains is a view, joining several table
 LookForDepartureStation = connection.prepareStatement("SELECT * from Journey where departure = ?");

In another method : 在另一种方法中:

    public List<Train> WhenTrain(String departureStation, String arrivalStation, java.util.Date dateBefore, java.util.Date dateAfter) {

        ArrayList<Train> TrainList= new ArrayList<>();

        try {


            java.sql.Date begin = new java.sql.Date(dateBefore.getTime());
            java.sql.Date end = new java.sql.Date(dateAfter.getTime());


            LookForDepartureStation.setString(1, departureStation);
            ResultSet test1 = LookForDepartureStation.executeQuery();

            if(test1.next()){

                  LookForDepartureStation.close();
                  LookForArrivalStation.setString(1, arrivalStation);
                  ResultSet test2 = LookForArrivalStation.executeQuery();

                  if(test2.next()) {
                      LookForArrivalStation.close();

                      AllTrains.setString(1, departureStation);
                      AllTrains.setString(2, arrivalStation);
                      AllTrains.setDate(3, begin);
                      AllTrains.setDate(4, end);

                      ResultSet rs = AllTrains.executeQuery();

                         while(rs.next()){
                               TrainList.add(new Train(rs.getInt(1), 

    rs.getString(2), rs.getString(3), rs.getDate(4), rs.getDate(5))); 
    // Train is an object to take all those.
    // AllTrains contains  TrainID (an oracle integer), departure (varchar2), arrival (varchar2), departurehour (sql oracle DATE), arrivalhour (sql oracle DATE)


           }
                   // AllTrains.close();
                     return ListeTrains;
                  }
                  else {
                      System.out.println("wrong input on arrival station");
                    //  AllTrains.close();
TrainApp.Alltrains(this);
                      return TrainList;
                  }
            } 
            else {
               System.out.println("wrong input on departure station");

               return TrainList;
            }

        } catch (SQLException error) {
            error.printStackTrace();

           return TrainList;
      }
             catch(NullPointerException e) {
              System.out.println("Station not found");
              e.printStackTrace();
              TrainApp.Alltrains(this); // calling back static method to try again the input.
               return TrainList;
          }

}      

When i try to pass Upperdate in the method, debugger shows that the variable contains : "1 janv. 0003 00:00:00" (I tried with 03-11-1993 actually). 当我尝试在方法中传递Upperdate时,调试器显示该变量包含:“ 1 janv。0003 00:00:00”(我实际上尝试过1993年3月11日)。 Moreover i don't think it will put the date i want in the Train object, i think i messed that up too. 而且我不认为它将把我想要的日期放在Train对象中,我想我也弄错了。

The program ends without showing me what is in the list (the instructions after the method call, as you see in the 2nd code quote here). 程序结束时没有向我显示列表中的内容(方法调用后的指令,如您在此处的第二个代码引用所示)。

Without knowing the values of upperDate and lowerDate it's hard to see why they are not parsed correctly. 如果不知道upperDate和lowerDate的值,很难理解为什么它们没有被正确解析。

The problem with the query is that java.sql.Date rounds the java.util.Date value in input to the day, ie it resets the time part. 该查询的问题在于java.sql.Date将输入中的java.util.Date值四舍五入为日期,即它重置了时间部分。 You must use java.sql.TimeStamp if you want to query and retrieve the correct results with the time part. 如果要查询和检索带有时间部分的正确结果,则必须使用java.sql.TimeStamp Try change begin and end type to java.sql.TimeStamp and rs.getDate(4), rs.getDate(5) to rs.getTimestamp(4), rs.getTimestamp(5) 尝试将beginend类型更改为java.sql.TimeStamprs.getDate(4), rs.getDate(5)更改为rs.getTimestamp(4), rs.getTimestamp(5)

The misunderstanding usually starts because the type Date in Oracle contains also the time part, but in other RDBMS the date type represents "only" a date 误解通常是由于Oracle中的日期类型还包含时间部分而引起的,但是在其他RDBMS中,日期类型表示“仅”日期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM