我在这个日期转换程序上有点困惑。我试图让它从数字mm / dd / yy格式转换为标准的月/日/年格式。我确定它是一个我无法看到的简单修复。任何建议将不胜感激。
所以它应该运行这样的东西:
以mm dd yyyy:11 20 1981
的格式输入日期您输入的日期是1981年11月20日。
输入另一个日期? (是/否)
package dateconverter;
import java.util.Scanner;
public class DateConverter {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int monthValue;
int dayValue;
int yearValue;
int[] daysOfMonth = {12, 31, 28, 31, 30, 31, 30, 31, 30, 31};
final String[] monthNames
= new String[]{"Jan", "Feb", "March", "April", "May",
"Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"};
while (true) {
// Gets date from the user.
System.out.print("Enter a date in the format mm dd yyyy: ");
monthValue = console.nextInt();
dayValue = console.nextInt();
yearValue = console.nextInt();
// Examine the month, day, year.
// Value for the month, day, year that is entered.
// If it is not the range of the accepted value, throw an exception.
try { // MonthException
if (monthValue < 1 || monthValue > 12)
throw new MonthException();
}
catch (MonthException e) {
System.out.println(e.getMessage());
}
try { // Day Exception
if (dayValue < 1 && dayValue > 31 )
throw new DayException();
}
catch (DayException e) {
System.out.println(e.getMessage());
}
try { // Year Exception
if (yearValue <= 1000 && yearValue >= 3000)
throw new YearException();
}
catch (YearException e) {
System.out.println(e.getMessage());
}
try { // Leap Year
if ((yearValue % 4 == 0) && (dayValue > 31))
throw new DateException();
}
catch (DateException e) {
System.out.println(e.getMessage());
}
console.nextLine(); // To flush input buffer.
System.out.print("Enter another date? (yes/no) ");
String response = console.nextLine();
if (!response.toUpperCase().equals("no")) {
System.exit(0);
}
}
}
private static class MonthException extends RuntimeException {
public MonthException() {
super("Invalid month value entered, month exceeds excepted value."
+ "Please try again.");
}
}
private static class DateException extends RuntimeException {
public DateException() {
super("Entered date is a leap year.");
}
}
}
class YearException extends RuntimeException {
public YearException() {
super("Values between 1000 and 3000 are only allowed,"
+ " Please try again.");
}
}
class DayException extends RuntimeException {
public DayException() {
super("Invalid day value entered, only accept values between 1 and 31."
+ " Please try again.");
}
}
答案 0 :(得分:1)
private String getFormatedDate(String date) {
SimpleDateFormat sf = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat sfFormate = new SimpleDateFormat("MMM/dd/yyyy");
try {
return sfFormate.format(sf.parse(date))+ "";
} catch (ParseException e) {
e.printStackTrace();
return "";
}
}
并将此功能称为
getFormatedDate("11/19/2014");
如果它适合你,请标记为。