You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写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 SimpleDateFormat instances using the same dd/MM/yyyy pattern. I changed the second one (i) to use dd-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 use i.format(m) which takes the parsed Date object and turns it into the formatted string.
  • Added error handling: The catch block 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:

  1. The program prompts you to enter a date in dd/MM/yyyy format (e.g., 25/12/2024).
  2. It parses that input string into a Date object using the first formatter (d).
  3. Then it converts that Date object into the dd-MM-yyyy string format using the second formatter (i) and prints it out (e.g., 25-12-2024).
  4. If you enter something invalid (like 30/02/2024 or 10/13/2024), it'll show an error message explaining the issue.

内容的提问来源于stack exchange,提问作者Divya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:34:50