I'm really reminded now, but I'm addicted to it ...
When I was writing a program to format a date into a string, I encountered a phenomenon that the number of years advanced by 1900 for some reason. In the first place, the constructor that takes the "year, month, day" of the Date class is deprecated, so it is certainly a story that you do not have to use it. However, it is an example of a failure that happens when you use it carelessly without knowing it.
DateTest.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
int year = 2018;
int month = 5;
int dayOfMonth = 6;
Date todayDate = new Date(year, month, dayOfMonth);
DateFormat dateFormat = SimpleDateFormat.getDateInstance();
System.out.println(dateFormat.format(todayDate));
}
}
As in this example, if you create a Date instance based on the date given by the ʻint type and create aFormatwithDateFormat`,
3918/06/06
This year is 2018, but it is 3918. It's just 1900.
This is a specification of the java.util.Date class.
Also written in Date (Java Platform SE 8) However, the value of year received by this constructor is the implementation that takes the value obtained by subtracting 1900 from the year of the calendar.
As is well known to those who are familiar with it, the constructor that takes the date of java.util.Date is deprecated from JDK1.1 (it appears when you search for Date, so I'm likely to use it). Instead, you should instantiate it with java.util.Calendar and then get a Date instance with Calendar # getDate.
DateTest.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateTest {
public static void main(String[] args) {
int year = 2018;
int month = 5;
int dayOfMonth = 6;
Calendar todayDate = Calendar.getInstance();
todayDate.set(year, month, dayOfMonth);
DateFormat dateFormat = SimpleDateFormat.getDateInstance();
System.out.println(dateFormat.format(todayDate.getTime()));
}
}
2018/07/06
The date is now output normally.
Recommended Posts