输入和输出日期类Java



我正在做一个类日期项目,用户输入日期并将日期输出为3种不同的格式。a) 年/月/日b) 年月日c) DDD,YYYY(年份日期)。

我被困在一个点上,在那里输出a部分的结果。以下是我到目前为止得到的

import java.util.Scanner;
public class Implementation
{
    private static int month;
    private static int day;
    private static int year;
    private static final int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    public static void Date(String args[])
    {
        Scanner input = new Scanner(System.in);
        while(year != -1)
        {    
        System.out.print("Enter month: ");
        month = input.nextInt();
        System.out.print("Enter day: ");
        day = input.nextInt();
        System.out.print("Enter year: ");
        year = input.nextInt();
        System.out.printf("nMM/DD/YYYY: %d/%d/%d");
        System.out.printf("nMonth DD/YYYY: ");
        System.out.println("nDDD YYYY: n");
        }    
    }    
    public Implementation(int month, int day, int year)
        {
        if (month <= 0 || month > 12)
            throw new IllegalArgumentException(
            "month (" + month + ") must be 1-12");
        if (day <= 0 | (day > daysPerMonth[month] && !(month == 2 && day == 29)))
            throw new IllegalArgumentException
            ("day (" + day + ") out-of-range for the specified month and year");
        if (month == 2 && day == 29 && !(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)))
            throw new IllegalArgumentException
            ("day (" + day + ") out-of-range for the specified month and year");
        this.month = month;
        this.day = day;
        this.year = year;
        }
    public String toString()
    {
        return String.format("%d/%d/%d", month, day, year);
    }
}

我应该在System.out.printf("nMM/DD/YYYY: %d/%d/%d");后面放些什么来显示结果(有效的月份、日期和年份)。我还没有做其他两个选项。我是初学者,对这个项目很失望。有人帮忙吗?

您可能忘记了使用SimpleDateFormat。您正在使用String.format。格式化日期时最好避免。你可以试试这个-

SimpleDateFormat formatter = new SimpleDateFormat("mm/dd/yyyy"); //for (a)
Date dateString = formatter.parse(strDate);   

感谢

尝试以下操作:

Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, 2014);
c.set(Calendar.MONTH, 10);
c.set(Calendar.DAY_OF_MONTH, 21);
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(format.format(c.getTime()));
Output:
21-10-2014

当您想像下面的行一样使用printf输出一些文本时,您需要告诉该方法您实际希望它打印什么。

对于这条线路:

System.out.printf("nMM/DD/YYYY: %d/%d/%d");

您需要将月份、日期和年份的变量放入printf方法中,否则该方法将只打印双引号中的内容。

因此,正确的方法是:

System.out.printf("nMM/DD/YYYY: %d/%d/%d", month, day, year);

Java将用参数中逗号后面的变量中的值替换%d符号,并打印出文本。第一个%d被第一个变量(在本例中为"month")替换,第二个%d被第二个变量("day")替换等等。(当变量为int时使用%d,当变量为float时使用%f,等等)

关于Java字符串格式化的文档

最新更新