编写Java程序,获取格式为“dd-MM-yyyy”的日期字符串
Fixing the Java Program to Get Date in "dd-MM-yyyy" Format
Alright, let's get this code working properly to output dates in the requested dd-MM-yyyy format. Here's the complete, corrected version of your code:
import java.util.Scanner; import java.text.SimpleDateFormat; import java.util.Date; import java.text.ParseException; import java.text.DateFormat; import java.util.Locale; class Main { public static void main(String[] args)throws ParseException{ Scanner sc=new Scanner(System.in); System.out.println("enter the date"); String p=sc.nextLine(); SimpleDateFormat d=new SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH); // Updated the pattern to our target format: dd-MM-yyyy SimpleDateFormat i=new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH); try { Date m=d.parse(p); // Format the parsed date into the desired string format System.out.println("Formatted date: " + i.format(m)); } catch (ParseException e) { // Handle invalid input gracefully System.out.println("Oops! That's not a valid date in dd/MM/yyyy format. Please try again."); e.printStackTrace(); } sc.close(); // Clean up the scanner resource } }
Key Changes I Made:
- Adjusted the output formatter: The original code had both
SimpleDateFormatinstances using the samedd/MM/yyyypattern. I changed the second one (i) to usedd-MM-yyyy—this is what converts the parsed date into your desired string format. - Completed the output line: Added the missing part of
System.out.println()to usei.format(m)which takes the parsedDateobject and turns it into the formatted string. - Added error handling: The
catchblock now catches invalid date inputs (like dates with invalid days/months) and gives a clear message to the user instead of just crashing. - Cleaned up resources: Added
sc.close()to properly close the scanner once we're done with it.
How It Works:
- The program prompts you to enter a date in
dd/MM/yyyyformat (e.g.,25/12/2024). - It parses that input string into a
Dateobject using the first formatter (d). - Then it converts that
Dateobject into thedd-MM-yyyystring format using the second formatter (i) and prints it out (e.g.,25-12-2024). - If you enter something invalid (like
30/02/2024or10/13/2024), it'll show an error message explaining the issue.
内容的提问来源于stack exchange,提问作者Divya
相关产品推荐
相关产品推荐

