gpt4 book ai didi

java - 如何使用字符串作为输入创建并输出日期对象?即 "13/04/1998"

转载 作者:行者123 更新时间:2023-12-01 13:52:57 25 4
gpt4 key购买 nike

此设置不起作用。当我打印 v1 时,我得到了格式错误的错误日期,因为它包含的时间为 00:00:0000。

有没有办法重写 Date 对象的格式化方法(如果有的话)?

public class Vehicle
{

//**********Declarations**********
private String manufacturer;
private String model;

//********** Declaring Customer object **********
private Customer customer = null;

private String VIN;
private Date dateOfManufacture;
private Date dateOfSale = null;
private Boolean sold = false;
private char taxBand;
private int costOfVehicle;


//**********Constructor**********
public Vehicle(String man, String mod, Customer custName, String VIN, String dateOfMan, char taxBand, int costOfVehicle)
{
this.manufacturer = man;
this.model = mod;

this.customer = custName;

this.VIN = VIN;

Date newDate = new Date(dateOfMan);
this.dateOfManufacture = newDate;

this.taxBand = taxBand;
this.costOfVehicle = costOfVehicle;
}

public Date getDateOfManufacture()
{
return dateOfManufacture;
}


public void setDateOfManufacture(Date dateOfManufacture)
{
this.dateOfManufacture = dateOfManufacture;
}


public Date getDateOfSale()
{
return dateOfSale;
}


public void setDateOfSale(Date dateOfSale)
{
this.dateOfSale = dateOfSale;
}

}


//*******Driver class creating a new Vehicle object *******

Vehicle v1 = new Vehicle("Ford", "Fiesta", null, "123abc", "12/03/2000", 'c', 3000);

最佳答案

要从 String 获取Date,您可以使用 SimpleDateFormat,如下所示:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyy");
Date myDate = simpleDateFormat.parse("13/04/1998");

关于java - 如何使用字符串作为输入创建并输出日期对象?即 "13/04/1998",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19822703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com