如何在Java中将日期转换为另一个日期字符串?

huangapple go评论75阅读模式
英文:

How to convert a date into another date as a String in Java?

问题

String oldDate = "05-Apr-23";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
Date dt = null;
try {
    dt = sdf.parse(oldDate);
} catch (ParseException e) {
    throw new CustomInternalServerException(oldDate + " 不是有效日期");
}

SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yy");
return sdf1.format(dt);
英文:

I want to convert a date format into another date format. For example, I have this String "05-Apr-23" and I want to convert it into this String "05/04/23". And I did this implementation but it's not working.

String oldDate = "05-Apr-23";
SimpleDateFormat sdf = new SimpleDateFormat("dd-mmm-yy");
Date dt = null;
try {
    dt = sdf.parse(oldDate);
} catch (ParseException e) {
    throw new CustomInternalServerException(oldDate + "is not a valid date");
}

SimpleDateFormat sdf1 = new SimpleDateFormat("dd/mm/yy");
return sdf1.format(dt);

I get the exception ParseException: UnparseableDate: "05-Apr-23". Any feedback will be appreciated! Thank you!

答案1

得分: 4

只需要翻译的部分:

You did only one small mistake you have to use MMM instead of mmm , m is used for minute and M is for month.

change as follow

dd-mmm-yy to dd-MMM-yy
dd/mm/yy to dd/MM/yy

and one more mistake at last you have to return sdf1 not sdf.

英文:

You did only one small mistake you have to use MMM instead of mmm , m is used for minute and M is for month.

change as follow

dd-mmm-yy to dd-MMM-yy
dd/mm/yy to dd/MM/yy

and one more mistake at last you have to return sdf1 not sdf.

答案2

得分: 3

java.time

不要使用被淘汰的日期类。DateSimpleDateFormat - 不要使用!LocalDateDateTimeFormatter - 是的!

并且格式化模式是区分大小写的。对于月份的缩写名称,请使用大写‘MMM’。

指定一个Locale,用于确定本地化该月份名称的人类语言和文化规范。

String oldDate = "05-Apr-23";
DateTimeFormatter dfFrom = DateTimeFormatter.ofPattern("dd-MMM-yy").withLocale(Locale.US);
DateTimeFormatter dfTo = DateTimeFormatter.ofPattern("dd/MM/yy");
String newDate = dfTo.format(LocalDate.parse(oldDate, dfFrom));
System.out.println(newDate);
英文:

java.time

Don't use superseded date classes. Date, SimpleDateFormat - no! LocalDate , DateTimeFormatter - yes!

And the formatting pattern is case-sensitive. For abbreviated name of month, use uppercase ‘MMM’.

Specify a Locale to be used in determining the human language and cultural norms for localizing that name of month.

String oldDate = "05-Apr-23";
DateTimeFormatter dfFrom = DateTimeFormatter.ofPattern("dd-MMM-yy").withLocale( Locale.US );
DateTimeFormatter dfTo = DateTimeFormatter.ofPattern("dd/MM/yy");
String newDate = dfTo.format(LocalDate.parse(oldDate, dfFrom));
System.out.println(newDate);

huangapple
  • 本文由 发表于 2023年4月6日 20:29:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75949538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定