I was studying about Date,
I feel that there were some parts that I didn't understand very well in these two points, so I will summarize them.
Actually, it was swamped because the fields of the Calendar class were not well understood, and it seems that Java 8 has a new date API and it can be handled a little more intuitively, but it is also a primitive Date class. I felt that it was better to start understanding, so I tried to draw while verifying various things in my own way.
__ Version using Calendar class is also helpful __
TenDaysDate.java
import java.text.SimpleDateFormat;
import java.util.Date;
public class TenDaysDate {
public static void main(String[] args) {
//Change the long value of Date type to get the date 10 days later
Date d = new Date(); //Get the current date and time
long ts = System.currentTimeMillis(); //Get the current epoch milliseconds
//Compare the return value of getTime method of Date type with the value of currentTimeMillis
System.out.println("d.getTime:\t\t\t" + d.getTime()); // Date.getTime value
System.out.println("currentTimeMillis:\t" + ts); //value of currentTimeMillis
if(ts == d.getTime()) System.out.println("Together"); //long values match
//Display Date type date information by specifying the format
SimpleDateFormat f = new SimpleDateFormat("yyyy year MM month dd day"); //Specify display format
System.out.println("Today's date:\t" + f.format(d)); //Pass Date type argument to SimpleDateFormat type
//Add 10 days worth of milliseconds with the Date type setTime method and change to date information 10 days later.
d.setTime(d.getTime() + (long)(24 * 60 * 60 * 1000) * 10); // ()Is a millisecond of the day
System.out.println("Date 10 days later:\t" + f.format(d)); //Pass to SimpleDateFormat type as an argument of Date type
}
}
Output result
d.getTime: 1602415769204
currentTimeMillis: 1602415769204
Together
Today's date:October 11, 2020
Date 10 days later:October 21, 2020
d.getTime(); //Epoch milliseconds are returned
d.setTime(Epoch milliseconds); // Epoch millisecondsを引数に渡して日付情報をセットする
January 1, 1970 00:00:00 Milliseconds elapsed from UTC
Also known as Unix Time
One day's worth of milliseconds is 24 * 60 * 60 * 1000
. Multiply this by 10 for 10 days worth of milliseconds.
Also, by setting getTime () + 24 * 60 * 60 * 1000 * 10
, you can get the date information 10 days after the lapse of milliseconds from the current time.
Do you need to cast to a long type as (long) 24 * 60 * 60 * 1000
in some cases?
If a leap year comes out 10 years later or something like that, even if the millisecond one year later is 24 * 60 * 60 * 1000 * 365 * 10
, it will not be the same month and day 10 years later. ..
When calculating over a long span, you have to add it to the year field etc. It's complicated.
Recommended Posts