[英]Converting string date to date
我將如何將格式為24/04/2012的String日期轉換為格式為24-Apr-12的日期變量,以后可以將其傳遞到我的Oracle數據庫中。
我已經嘗試過了,但是它說字符串日期是不可解析的:
DateFormat format = new SimpleDateFormat("dd-MMM-yy");
Date newDate = (Date) format.parse(date);
我認為您在解析和格式化時會感到困惑,請嘗試以下操作:
String old_date = "24/04/2012";
DateFormat old_format = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = (Date) old_format.parse(old_date);
DateFormat new_format = new SimpleDateFormat("dd-MMM-yy");
String date = new_format.format(newDate);
System.out.println(date);
您的日期格式應為“ dd / MM / yyyy”
您正在反向執行此操作:
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = format.parse(date);
DateFormat formatOutput = new SimpleDateFormat("dd-MMM-yyyy");
String output = formatOutput.format(newDate);
但是,如果您正在執行的操作是將日期傳遞給Oracle,則應該使用PreparedStatement
SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yy");
DateTime newDate = sdf.format(date);
嘗試DateFormat format = new SimpleDateFormat("dd/MM/yyyy")
為什么不嘗試使用java.sql.Date。
例如:
Date newDate = new java.sql.Date(date.getTime());
因此,您可以僅給出日期的通用sql對象。
Java的Date類在很多情況下很難使用。 我建議使用更好的Joda Time類:
DateTimeFormatter oldFormat = DateTimeFormat.forPattern("dd/mm/yyyy");
DateTimeFormatter newFormat = DateTimeFormat.forPattern("dd-MMM-yy");
DateTime dateTime = oldFormat.parseDateTime("24/04/2012");
String newDate = newFormat.print(dateTime);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.