将dd-MMM-yyyy转换为MM / dd / yyyy格式

时间:2012-08-30 11:12:52

标签: java sql-server

我的日期字符串为“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中插入此日期。

6 个答案:

答案 0 :(得分: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-2012MM/dd/yyyy - 这些格式不同。

日期解析器期望String与格式化程序的格式相同

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

答案 1 :(得分:3)

您应该使用:

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

然后重新格式化:

sdf.applyPattern("MM/dd/yyyy");
System.out.println(sdf.format(date));

答案 2 :(得分:1)

在sql server中:

你可以使用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

答案 3 :(得分:0)

更改SimpleDateFormat

SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");

答案 4 :(得分:0)

String deliverydate="02-SEP-2012";
SimpleDateFormat sdf=new SimpleDateFormat("MM-dd-yyyy");
Date date=sdf.parse(deliveryDate);

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

答案 5 :(得分:0)

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