2

我的日期字符串为“02-SEP-2012”。我想将其转换为 8/02/2012 格式。

String deliverydate="02-SEP-2012";
SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy");

Date date=sdf.parse(deliveryDate);

这给了我

java.text.ParseException: Unparseable date: "01-Sep-2012"

如何解析这个?我想在 MS SQL 中插入这个日期。

4

6 回答 6

5

2018/Java 10

String deliverydate="02-SEP-2012";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("dd-MMM-yyyy")
                .toFormatter(Locale.UK);
LocalDate ld = LocalDate.parse(deliverydate, formatter);
System.out.println(ld);

原始答案

查看两个字符串,02-SEP-2012并且MM/dd/yyyy- 它们的格式不同。

日期解析器期望字符串与格式化程序的格式相同

String deliverydate="02-SEP-2012";
SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");

Date date=sdf.parse(deliveryDate);

sdf=new SimpleDateFormat("MM/dd/yyyy");
System.out.println(sdf.format(date));
于 2012-08-30T11:18:17.833 回答
2

你应该使用:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Date date = sdf.parse(deliveryDate);

然后重新格式化:

sdf.applyPattern("MM/dd/yyyy");
System.out.println(sdf.format(date));
于 2012-08-30T11:16:07.443 回答
1

在 sql 服务器中:

你可以使用 convert() 函数..

你可以试试

Insert into <table> (date_col,<othercolumns>)
select CONVERT(date,'02-SEP-2012'),<othercolumns>

例子:

declare @date varchar(20) ='02-SEP-2012'
select CONVERT(date,@date)

结果:

2012-09-02
于 2012-08-30T11:17:03.760 回答
0
String deliverydate="02-SEP-2012";
SimpleDateFormat sdf=new SimpleDateFormat("MM-dd-yyyy");
Date date=sdf.parse(deliveryDate);

你试过这个“-”而不是“/”。

于 2012-08-30T11:18:24.910 回答
0

更改SimpleDateFormat

SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
于 2012-08-30T11:17:15.300 回答
0

如果提供的日期不是有效格式,则使用 parse(String source) 方法可能会引发 java.text.ParseException 异常。因此您应该使用有效格式。

于 2012-08-30T11:38:33.937 回答