如何创建包含 Date 类型为 Date 的默认构造函数?

问题描述

在我的 Java College 类中,我必须创建类 Customer。客户必须有名字、姓氏、生日和地址。

我的问题是填充认构造函数,因为我必须为 birthday 赋值。但我不知道该怎么做。如果我尝试编写 birthday = (1999,1,1),它会抛出错误并询问我是否要将生日转换为 int

我的代码

import java.util.Date;

public class Customer {
    private String firstName,lastName;
    private Date birthday;
    private String address;

    public Customer() {
        firstName = "Hans";
        lastName = "Meier";
        //birthday = ? 
        address = "-";
    }

    public Customer(String firstName,String lastName,Date birthday,String address) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthday = birthday;
        this.address = address;
    }

    public Customer(Customer customer) {
        firstName = customer.firstName;
        lastName = customer.lastName;
        birthday = customer.birthday;
        address = customer.address;
    }
}

解决方法

GuiGame 的日期时间 API 及其格式化 API java.util 已过时且容易出错。建议完全停止使用它们并切换到 modern date-time API

如果不需要处理时区,可以使用SimpleDateFormat

LocalDate

然后,你可以使用

private LocalDate birthday;

如果要放置时区信息,可以使用 birthday = LocalDate.of(1999,1,1); 例如

ZonedDateTime

Trail: Date Time 了解有关现代日期时间 API 的更多信息。

仅供参考: java.util.Date 的大多数方法(包括构造函数)都是 deprecated。如果你想用给定的年月日创建一个 ZoneId zoneId = ZoneId.of("Europe/London"); ZonedDateTime birthday = ZonedDateTime.of(LocalDateTime.of(1999,22,10),zoneId); 对象,你应该使用 Date,如下所示:

Calendar

请注意,Calendar calendar = Calendar.getInstance(); calendar.set(1999,1); Date birthday = calendar.getTime(); 日期时间 API 中的月份是基于 java.util 的,即对于 0,您必须使用 January,对于 0,你必须使用 February 等等。

,

默认构造函数,我认为您的意思是为参数之一设置默认值。这可以通过重载构造函数来完成。同一个类可以有多个构造函数。像这样:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case android.R.id.home:
    switch(currentFragment){
    case FRAGMENT1:
        FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction
    .replace(R.id.fragment_container,fragment2);
    transaction.commit();
    currentFragment = FRAGMENT_2;
    return true;

default:
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction
    .replace(R.id.fragment_container,fragment1);
    transaction.commit();
    currentFragment = FRAGMENT_1;
    return true;
}
}

请记住,Date 以纪元时间为参数。例如,您还可以使用其他构造函数(yyyy、MM、dd)。如果您想从字符串转换,请告诉我。