The date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
If you do not have to deal with timezone, you can use LocalDate
:
private LocalDate birthday;
and then, you can use
birthday = LocalDate.of(1999, 1, 1);
If you want to put timezone information, you can use ZonedDateTime
e.g.
ZoneId zoneId = ZoneId.of("Europe/London");
ZonedDateTime birthday = ZonedDateTime.of(LocalDateTime.of(1999, 1, 1, 22, 10), zoneId);
Learn more about the modern date-time API from Trail: Date Time.
FYI: Most of the methods, including the constructors, of java.util.Date
are deprecated. If you want to create an object of Date
with some given year, month and day, you should use Calendar
as shown below:
Calendar calendar = Calendar.getInstance();
calendar.set(1999, 0, 1);
Date birthday = calendar.getTime();
Note that the month in java.util
date-time API is 0
-based i.e. for January
, you have to use 0
, for February
, you have to use 1
and so on.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…