Java 本地日期示例
程序来演示 LocalDate 类的方法,例如 now()、minusDays()、plusDays()。
import java.time.LocalDate;
public class LocalDateExample1 {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalDate yesterday = date.minusDays(1);
LocalDate tomorrow = yesterday.plusDays(2);
System.out.println("Today date: "+date);
System.out.println("Yesterday date: "+yesterday);
System.out.println("Tomorrow date: "+tomorrow);
}
}
输出:
Today date: 2017-01-13
Yesterday date: 2017-01-12
Tomorrow date: 2017-01-14
import java.time.LocalDate;
public class LocalDateExample2 {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2017, 1, 13);
System.out.println(date1.isLeapYear());
LocalDate date2 = LocalDate.of(2016, 9, 23);
System.out.println(date2.isLeapYear());
}
}
输出:
false
true
import java.time.*;
public class LocalDateExample3 {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2017, 1, 13);
LocalDateTime datetime = date.atTime(1,50,9);
System.out.println(datetime);
}
}
输出:
2017-01-13T01:50:09
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateExample4
{
public static void main(String ar[])
{
// Converting LocalDate to String
// Example 1
LocalDate d1 = LocalDate.now();
String d1Str = d1.format(DateTimeFormatter.ISO_DATE);
System.out.println("Date1 in string : " + d1Str);
// Example 2
LocalDate d2 = LocalDate.of(2002, 05, 01);
String d2Str = d2.format(DateTimeFormatter.ISO_DATE);
System.out.println("Date2 in string : " + d2Str);
// Example 3
LocalDate d3 = LocalDate.of(2016, 11, 01);
String d3Str = d3.format(DateTimeFormatter.ISO_DATE);
System.out.println("Date3 in string : " + d3Str);
}
}
输出:
Date1 in string : 2021-09-13
Date2 in string : 2002-05-01
Date3 in string : 2016-11-01
import java.time.LocalDate;
// String to LocalDate in java 8
public class LocalDateExample5
{
public static void main(String ar[])
{
// Example 1
String dInStr = "2011-09-01";
LocalDate d1 = LocalDate.parse(dInStr);
System.out.println("String to LocalDate : " + d1);
// Example 2
String dInStr2 = "2015-11-20";
LocalDate d2 = LocalDate.parse(dInStr2);
System.out.println("String to LocalDate : " + d2);
}
}
输出:
String to LocalDate : 2011-09-01
String to LocalDate : 2015-11-20