[英]How to Convert String type date to date for entry into oracle DB - Java
Incoming date format id 2014-11-03 00.00.00.0 and need to be converted to either 03/11/2014 or 03-Nov-2014.传入日期格式 id 2014-11-03 00.00.00.0,需要转换为 03/11/2014 或 03-Nov-2014。
What could be the best possible and smallest code?什么可能是最好的和最小的代码?
OK, so you have a String
with the value 2014-11-03 00.00.00.0
and you want to insert that value in a DATE
field inside a Oracle Database Table, using Java's JDBC?好的,所以您有一个值为
2014-11-03 00.00.00.0
的String
,并且您想使用 Java 的 JDBC 将该值插入到 Oracle 数据库表内的DATE
字段中?
Well, first, convert that String
into a Date
object using a SimpleDateFormat object:好吧,首先,使用SimpleDateFormat对象将该
String
转换为Date
对象:
String s = "2014-11-03 00.00.00.0";
Date d = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss.S").parse(s);
Then, if you are using plain statements, reformat it the way Oracle would accept it in an SQL INSERT
command, using again a SimpleDateFormat
object:然后,如果您使用的是普通语句,请按照 Oracle 在
SQL INSERT
命令中接受它的方式重新格式化它,再次使用SimpleDateFormat
对象:
String sd = new SimpleDateFormat("dd/MM/yyyy").format(d);
and insert it into your Statement:并将其插入您的声明中:
cn.createStatement().executeUpdate("INSERT INTO TABLE(...) VALUES(" + sd + ");
I would recommend you to better use a PreparedStatement instead of a plain SQL INSERT
statement so your statement is sanitized:我建议您更好地使用PreparedStatement而不是普通的
SQL INSERT
语句,以便对您的语句进行清理:
PreparedStatement ps = cn.prepareStatement("INSERT INTO table VALUES(?, ?, ?)");
And then, insert your date as a Date object without the need of formatting into a String:然后,将您的日期作为 Date 对象插入,无需格式化为字符串:
ps.setDate([index of the field to insert], d);
If you're using java 8 there's a very useful date format class java.time.format.DateTimeFormatter
With that class you can do something like these:如果您使用的是 java 8,则有一个非常有用的日期格式类
java.time.format.DateTimeFormatter
使用该类,您可以执行以下操作:
LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH.mm.ss");
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/DD/YYYY");
String newText = parsedDate.format(formatter2);
试试这个代码:
Date d = new SimpleDateFormat("dd/MM/yyyy").parse(date);
In java 8 getting a java.sql.Date
(= java.util.Date
with zero time) from that string may use a formatter, but as the string is almost ISO standard:在 java 8
java.util.Date
,从该字符串java.util.Date
java.sql.Date
(= java.util.Date
with zero time) 可能会使用格式化程序,但由于该字符串几乎是 ISO 标准:
LocalDateTime x = LocalDateTime.parse("2014-11-03T00:00:00.0");
one could patch the string as:可以将字符串修补为:
LocalDateTime t = LocalDateTime.parse("2014-11-03 00.00.00.0"
.replaceFirst(" ", "T") // Make ISO
.replaceFirst("\\.", ":")
.replaceFirst("\\.", ":"));
java.sql.Date time = java.sql.Date.valueOf(t.toLocalDate());
Or或者
LocalDate t = LocalDate.parse("2014-11-03 00.00.00.0"
.replaceFirst(" .*$", "")); // Remove time part
java.sql.Date time = java.sql.Date.valueOf(t);
myPreparedStatement.setObject(
… ,
LocalDate.parse( "2014-11-03 00.00.00.0".substring( 0 , 10 ) )
);
What could be the best possible and smallest code?
什么可能是最好的和最小的代码?
There you go.你去吧。 But I do not recommend actually crunching so much into a single line.
但我不建议实际上将这么多内容压缩成一行。 The “best” code is rarely the “smallest” code.
“最好”的代码很少是“最小的”代码。
Other answers are correct.其他答案都是正确的。 But here is something shorter.
但这里有一些更短的东西。
First of all, you should not be submitting a date-only value to a database as a string.首先,您不应该将仅日期值作为字符串提交给数据库。 Submit as a date-only object.
作为仅限日期的对象提交。 Your JDBC driver will handle the details of communicating that to the database.
您的JDBC 驱动程序将处理与数据库通信的细节。
First extract your date value by calling String::substring
.首先通过调用
String::substring
提取您的日期值。 With padding zeros on month and day-of-month we know the first 10 digits are the date.通过在月和月日填充零,我们知道前 10 位数字是日期。
LocalDate ld = LocalDate.parse( "2014-11-03 00.00.00.0".substring( 0 , 10 ) );
If your JDBC driver complies with JDBC 4.2 or later, you can pass the LocalDate
directly via PreparedStatement::setObject
.如果您的 JDBC 驱动程序符合JDBC 4.2或更高版本,您可以直接通过
PreparedStatement::setObject
传递LocalDate
。
myPreparedStatement.setObject( … , ld );
…or perhaps: ……或者也许:
myPreparedStatement.setObject( … , ld , JDBCType.DATE );
If your driver does not comply, convert to the legacy class java.sql.Date
.如果您的驱动程序不符合要求,请转换为遗留类
java.sql.Date
。 Look to new methods added to the old classes.寻找添加到旧类中的新方法。
java.sql.Date sqlDate = java.sql.Date.valueOf( ld );
The approach described here assumes the input string was intended for UTC .此处描述的方法假定输入字符串用于UTC 。 If not, you need to adjust into UTC.
如果不是,则需要调整为 UTC。 Search Stack Overflow for posts on parsing a string as a
ZonedDateTime
.在 Stack Overflow 上搜索有关将字符串解析为
ZonedDateTime
。
This also works for me.这也适用于我。 a small utility method to generate a string value of a date that can be inserted into an Oracle Database Date Field, abit dirty but works.
一个生成日期字符串值的小实用方法,可以插入到 Oracle 数据库日期字段中,有点脏但有效。 first function uses Calender class and second one LocalDate ( Java8 or higher )
第一个函数使用 Calender 类,第二个使用 LocalDate(Java8 或更高版本)
1. 1.
/*
* Format Date for Presentation in format
* 19-DEC-2019 i.e. Oracle DB DD-MMM-YYYYY
*/
private String stringToDate(String inputDate) {
String finalDate = null;
if (inputDate == null)
return null;
try {
Date parseDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(inputDate);
// set your local time zone
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Africa/Lusaka"));
cal.setTime(parseDate);
String finalMonth = "";
int yearVal = cal.get(Calendar.YEAR);
int monthVal = cal.get(Calendar.MONTH); //returns value 0 to 11
int dayVal = cal.get(Calendar.DAY_OF_MONTH);
switch(monthVal) {
case 0:
finalMonth = "JAN";
break;
case 1:
finalMonth = "FEB";
break;
case 2:
finalMonth = "MAR";
break;
case 3:
finalMonth = "APR";
break;
case 4:
finalMonth = "MAY";
break;
case 5:
finalMonth = "JUN";
break;
case 6:
finalMonth = "JUL";
break;
case 7:
finalMonth = "AUG";
break;
case 8:
finalMonth = "SEP";
break;
case 9:
finalMonth = "OCT";
break;
case 10:
finalMonth = "NOV";
break;
case 11:
finalMonth = "DEC";
break;
}
finalDate = dayVal+"-"+finalMonth+"-"+yearVal;
} catch (ParseException e) {
e.printStackTrace();
}
return finalDate;
}
2. 2.
/*
* Format Date for Presentation in format
* 19-DEC-2019 i.e. Oracle DB DD-MMM-YYYYY
*/
private String stringToDateJava8(String inputDate) {
String finalDate = null;
if (inputDate == null)
return null;
try {
Date parseDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(inputDate);
String finalMonth = "";
LocalDate localDate = parseDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int yearVal = localDate.getYear();
int monthVal = localDate.getMonthValue(); //returns value 1 to 12
int dayVal = localDate.getDayOfMonth();
switch(monthVal) {
case 1:
finalMonth = "JAN";
break;
case 2:
finalMonth = "FEB";
break;
case 3:
finalMonth = "MAR";
break;
case 4:
finalMonth = "APR";
break;
case 5:
finalMonth = "MAY";
break;
case 6:
finalMonth = "JUN";
break;
case 7:
finalMonth = "JUL";
break;
case 8:
finalMonth = "AUG";
break;
case 9:
finalMonth = "SEP";
break;
case 10:
finalMonth = "OCT";
break;
case 11:
finalMonth = "NOV";
break;
case 12:
finalMonth = "DEC";
break;
}
finalDate = dayVal+"-"+finalMonth+"-"+yearVal;
} catch (ParseException e) {
e.printStackTrace();
}
return finalDate;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.