更好的显示出生日期方式

huangapple go评论72阅读模式
英文:

Better way to display date of birth

问题

我知道这是显示出生日期的最简单方法是否有更好或更专业的方法来显示我的出生日期或者有没有我可以使用的 Java 工具类这是迄今为止我唯一知道如何显示出生日期的方法

class DateOfBirth {
    int day;
    int month;
    int year;
    
    public int getDay() {
        return day;
    }
    
    public void setDay(int day) {
        this.day = day;
    }
    
    public int getMonth() {
        return month;
    }
    
    public void setMonth(int month) {
        this.month = month;
    }
    
    public int getYear() {
        return year;
    }
    
    public void setYear(int year) {
        this.year = year;
    }
    
    public void displayInfo() {
        System.out.printf("%d,%d,%d", day, month, year);
    }
}

class Tutorial {
    public static void main(String[] args) {
        DateOfBirth dob = new DateOfBirth();
        
        dob.setDay(9);
        dob.setMonth(9);
        dob.setYear(1996);
        dob.displayInfo();
    }
}
英文:

I know this is the simplest way to display date of birth, is there a better way or a more professional way to display my date of birth? or a java util tool that I can use? This is so far the only way I know how to display my date of birth.

 class dateofbirth
    {
    	int day;
    	int month;
    	int year;
    	
    	public int getDay()
    	{
    		return day;
    	}
    	public void setDay(int day)
    	{
    		this.day=day;
    	}
    	public int getMonth()
    	{
    		return month;
    	}
    	public void setMonth(int month)
    	{
    		this.month=month;
    	}
    	public int getYear()
    	{
    		return year;
    	}
    	public void setYear(int year)
    	{
    		this.year=year;
    	}
    	public void displayInfo()
    	{
    		System.out.printf("%d,%d,%d",day,month,year);
    	}
    }
    class Tutorial
    {
    	public static void main(String[]args)
    	{
    		dateofbirth dob=new dateofbirth();
    		
    		dob.setDay(9);
    		dob.setMonth(9);
    		dob.setYear(1996);
    		dob.displayInfo();
    	}
    }

答案1

得分: 4

你可以使用java.time中的LocalDate类来存储出生日期:

LocalDate dateOfBirth = LocalDate.of(1996, 9, 9);

然后你可以使用DateTimeFormatter来指定日期格式化模式对日期进行格式化:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
System.out.println(dateOfBirth.format(formatter));

输出结果:1996-09-09

英文:

You can use LocalDate of java.time to store Date of Birth

LocalDate dateOfBirth = LocalDate.of(1996, 9, 9);

Then you can use DateTimeFormatter to format your date also by specifying the pattern

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
System.out.println(dateOfBirth.format(formatter));

Output: 1996-09-09

huangapple
  • 本文由 发表于 2020年10月4日 21:09:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64195010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定