简体   繁体   English

如何将两个String变量转换为date和timestamp列以插入数据库

[英]How to convert two String variables to date and timestamp column to insert into database

I need your help in getting the proper format to insert the date and time informaiton which is retrieved from two different string variables from the database and to insert them (date and time) into Date and Time column in an another table. 我需要您的帮助,以获取正确的格式,以插入从数据库中两个不同的字符串变量中检索到的日期和时间信息,并将它们(日期和时间)插入另一个表的“日期和时间”列中。 The date is retrieved from the agreement date column which is: 从协议日期列中检索日期:

String agreement_date = "";
agreement_date=rs.getString("agr_date"); //format DD-MON-YYYY ex. 22-May-2014

And the time is retrieved from: 从以下位置检索时间:

String frm_time = rs.getString("FRM_TIME"); //format HH:MI ex.7:20

So now I need to combine both columns into one variable and to insert them in database column called transaction_dt_time and its type is dateTime(format dd/MM/YYYY HH:MI:SS AM/PM), So how can I do that? 因此,现在我需要将两列合并到一个变量中,并将其插入名为transaction_dt_time的数据库列中,并且其类型为dateTime(格式dd / MM / YYYY HH:MI:SS AM / PM),那我该怎么做?

You can concatenate these strings into datetime string and convert to date using SimpleDateFormat for example 您可以将这些字符串连接为datetime字符串,并使用SimpleDateFormat转换为日期,例如

SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
Date dateToInsert = format.parse(concatenatedDate);

use a simpledateformat() for the time, is your time 24hours? 请使用simpledateformat()作为时间,您的时间是24小时吗? how do we know if it's AM or PM? 我们怎么知道是上午还是下午?

SimpleDateFormat sdfTime = new SimpleDateFormat("HH:MI:SS"); //AM/PM?
String strTime = sdfTime.format(frm_time);

final_date = agreement_date.replaceAll("-","/");
String FinalDate = final_date + strTime;

I understand you are fetching the values in the resultset from a database. 我了解您正在从数据库中获取结果集中的值。 generally date and time are stored in database according to the datatype. 通常,日期和时间根据数据类型存储在数据库中。 Recommend to use a rs.getDate() and rs.getTime() to fetch these values instead of a String datatype. 建议使用rs.getDate()和rs.getTime()来获取这些值,而不是String数据类型。

Here is a sample code for your conversion 这是您进行转换的示例代码

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo  {

    public static void main(String[] args) {
        try{
            String date = "22-May-2015";
            String time = "7:20";
            String yourString = date+ " "+ time;
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
            Date parsedDate = dateFormat.parse(yourString);
            Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
            System.out.println(timestamp);
        }catch(Exception e){
            e.printStackTrace();
            //this generic but you can control another types of exception
            // look the origin of excption 
        }
    }
    }

Hope this helps! 希望这可以帮助!

您可以使用JPA 2.1及其AttributeConverter接口

java.time java.time

The other answers use legacy date-time classes, now supplanted by the java.time framework built into Java 8 and later. 其他答案使用遗留日期时间类,现在这些类已由 Java 8及更高版本中内置的java.time框架取代。

First, parse the date portion. 首先,解析日期部分。

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern( "mm-DD-yyyy" );
LocalDate localDate = LocalDate.parse( "22-May-2014" , dateFormatter );

Second, parse the time portion. 其次,解析时间部分。

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern( "h:m" );
LocalTime localTime = LocalTime.parse( "7:20" , dateFormatter );

Third, determine the time zone in which this value has meaning. 第三,确定该值有意义的时区。 Is this a Montréal time, a Paris time, or a Kolkata time? 这是蒙特利尔时间,巴黎时间还是加尔各答时间?

ZoneId zoneId = ZoneId.of( "America/Montreal" );

Combine into a ZonedDateTime . 合并为ZonedDateTime

ZonedDateTime zdt = ZonedDateTime.of( localDate , localTime , zoneId );

You may be able to pass this ZonedDateTime to your database via the setObject method on a PreparedStatement with a JDBC 4.2 compliant driver. 您可以使用与JDBC 4.2兼容的驱动程序,通过PreparedStatement上的setObject方法将此ZonedDateTime传递给数据库。 But if not, convert into the old java.sql.Timestamp type. 但是,如果不是,请转换为旧的java.sql.Timestamp类型。 That old class has a new method to facilitate conversion, which takes an Instant object. 那个旧类有一个方便转换的新方法,该方法带有一个Instant对象。 An Instant is a moment on the timeline in UTC with a resolution of nanoseconds. Instant是UTC时间线上的时刻,分辨率为纳秒。 We can extract an Instant from our ZonedDateTime . 我们可以从ZonedDateTime提取一个Instant

Instant instant = zdt.toInstant();
java.sql.Timestamp ts = java.sql.Timestamp.from( instant ); 

On your PreparedStatement , call setTimestamp . 在您的PreparedStatement ,调用setTimestamp

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

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