日期未在Java中正确格式化

日期未在Java中正确格式化,java,datetime,date-formatting,date,Java,Datetime,Date Formatting,Date,我正在尝试将格式为“yyyy-MM-dd”的日期格式化为“dd-MM,yyyy”,但对于某些日期,我得到的年份不正确 这是我的密码: DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); DateFormat targetFormat = new SimpleDateFormat("dd MMMM, yyyy"); Date date = originalFormat.parse(dob);

我正在尝试将格式为“yyyy-MM-dd”的日期格式化为“dd-MM,yyyy”,但对于某些日期,我得到的年份不正确

这是我的密码:

DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("dd MMMM, yyyy");
Date date = originalFormat.parse(dob);
dob = targetFormat.format(date);
输入:27-05-1999
产出:0032年10月19日


正如您所看到的,输入日期与输出日期不同。我不明白如何才能做到这一点

你的模式是错误的。您输入了
27-05-1999
,因此正确的日期格式为
dd-MM-yyyy

String dob = "27-05-1999";
DateFormat originalFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("dd MMMM, yyyy");
Date date = originalFormat.parse(dob);
dob = targetFormat.format(date);

System.out.println(dob);

您的输入是:27-05-1999,日期格式是:yyyy-MM-dd。您实际上使用了错误的日期格式

此代码将正常工作

String dob = "27-05-1999";
DateFormat sourceFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
DateFormat destFormat = new SimpleDateFormat("dd MMMM, yyyy", Locale.getDefault());
Date date = sourceFormat.parse(dob);
dob = destFormat.format(date);
System.out.println(dob);  // output : 27 May, 1999
查看输入格式,您输入了错误的格式

如果希望保持相同的输入格式,请使用以下代码

    DateFormat originalFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
    DateFormat targetFormat = new SimpleDateFormat("dd MM, yyyy");
    Date date = originalFormat.parse("27-05-1999");
    String dob = targetFormat.format(date);

    System.out.println(dob);
两种情况下的输出


27 051999

下面的代码应该可以让您了解这里的问题所在

问题在于这里的表达式

//String dob = "1999-05-27";
//DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

String dob = "27-05-1999";
DateFormat originalFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);

DateFormat targetFormat = new SimpleDateFormat("dd MMMM, yyyy");
Date date = originalFormat.parse(dob);
dob = targetFormat.format(date);
System.out.println(dob);
您还可以查看java文档中的详细表达式信息,以下url应该可以帮助您:


您的输入模式似乎是“dd-MM-yyyy”,我不明白您为什么认为这一年是输入的第一年您还没有切换到较新的Java日期和时间类?是什么阻碍了你?我推荐他们。我甚至认为他们会给你一个异常消息,提示你的尝试有什么问题(总是一件好事)。
//String dob = "1999-05-27";
//DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

String dob = "27-05-1999";
DateFormat originalFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);

DateFormat targetFormat = new SimpleDateFormat("dd MMMM, yyyy");
Date date = originalFormat.parse(dob);
dob = targetFormat.format(date);
System.out.println(dob);