英文:
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
不要使用被淘汰的日期类。Date
、SimpleDateFormat
- 不要使用!LocalDate
、DateTimeFormatter
- 是的!
并且格式化模式是区分大小写的。对于月份的缩写名称,请使用大写‘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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论