import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class DateTest {
/**
* Instant 时间戳
* Duration 持续时间、时间差
* LocalDate 只包含日期,比如:2018-09-24
* LocalTime 只包含时间,比如:10:32:10
* LocalDateTime 包含日期和时间,比如:2018-09-24 10:32:10
* Peroid 时间段
* ZoneOffset 时区偏移量,比如:+8:00
* ZonedDateTime 带时区的日期时间
* Clock 时钟,可用于获取当前时间戳
* java.time.format.DateTimeFormatter 时间格式化类
* @param args
*/
public static void main(String[] args) {
/**
* 当前时间
* 不包含 时,分,秒
*/
LocalDate localDate = LocalDate.now();
System.out.println("当前时间:" + localDate);
/**
* 构造指定日期
* 传入 年,月,日
*/
LocalDate localDate1 = LocalDate.of(2020, 7, 27);
System.out.println("构造指定日期:" + localDate1);
/**
* 获取 年 月 日信息
*/
System.out.printf("年=%d, 月=%d, 日=%d", localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth());
/**
* 比较两个日期是否相等
*/
System.out.println("日期是否相等=" + localDate.equals(localDate1));
/**
*
*/
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(2);
System.out.println("newTime=" + newTime);
LocalDate date = LocalDate.now();
LocalDate newDate = date.plus(2, ChronoUnit.WEEKS);
System.out.println("newDate=" + newDate);
// 解析日期
String dateText = "20200728";
LocalDate date2 = LocalDate.parse(dateText, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println("格式化之后的日期=" + date2);
// 格式化日期
dateText = date2.format(DateTimeFormatter.ISO_DATE);
System.out.println("dateText=" + dateText);
/**
* 日期和字符串的相互转换
*/
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 日期时间转字符串
LocalDateTime now = LocalDateTime.now();
String nowText = now.format(formatter);
System.out.println("nowText=" + nowText);
// 字符串转日期时间
String datetimeText = "2020-07-26 23:59:59";
LocalDateTime datetime = LocalDateTime.parse(datetimeText, formatter);
System.out.println(datetime);
/**
* 时区设置
*/
// 上海时间
ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime shanghaiZonedDateTime = ZonedDateTime.now(shanghaiZoneId);
// 东京时间
ZoneId tokyoZoneId = ZoneId.of("Asia/Tokyo");
ZonedDateTime tokyoZonedDateTime = ZonedDateTime.now(tokyoZoneId);
System.out.println("上海时间: " + shanghaiZonedDateTime.format(formatter));
System.out.println("东京时间: " + tokyoZonedDateTime.format(formatter));
}
}