将字符串日期转换为日期

时间:2012-04-24 14:41:14

标签: java date datetime

我如何将24/04/2012形式的字符串日期转换为日期变量,格式为24-Apr-12,稍后可以将其传递到我的Oracle数据库。

我试过这个,但它说字符串日期是不可解决的:

DateFormat format = new SimpleDateFormat("dd-MMM-yy");
Date newDate = (Date) format.parse(date);

7 个答案:

答案 0 :(得分:4)

我认为你混淆解析和格式化,试试这个:

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);

答案 1 :(得分:1)

您的日期格式应为“dd / MM / yyyy”

答案 2 :(得分:1)

你正在倒退:

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

答案 3 :(得分:0)

SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yy");
DateTime  newDate = sdf.format(date);

答案 4 :(得分:0)

尝试DateFormat format = new SimpleDateFormat("dd/MM/yyyy")

答案 5 :(得分:0)

为什么不尝试使用java.sql.Date。

例如:

Date newDate = new java.sql.Date(date.getTime());

所以你可以为日期提供一个通用的sql对象。

答案 6 :(得分:0)

在很多情况下,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);
相关问题