Java核心之常见时间日期
Java日期处理类Date详解
时间的基础知识
时区:整个地球分为二十四时区,每个时区都有自己的本地时间。 为了统一起见,使用一个统一的时间,称为全球标准时间(UTC,Universal Time Coordinated)。 TC与格林尼治平均时(GMT,Greenwich Mean Time,也翻译成:格林威治标准时间)差不多一样 CST(北京时间),北京时间,China standard Time,中国标准时间。在时区划分上,属东八区,比协调世界时早8小时,记为UTC+8。 时间戳:自1970年1月1日(08:00:00GMT)至当前时间的总秒数,它也被称为Unix时间戳(unix Timestamp),广泛的运用在知识产权保护、合同签字、金融帐务、电子报价投标、股票交易等方面 格式多种:2050-10-3110:11:11、2050/10/3110/10:10年、月、日、周几等 背景:程序代码中怎么表示时间呢?我需要获取当前时间怎么办 ava.util包提供了Date类来封装当前的日期和时间 构造函数
Date()
Date(long millisec)
long getTime()
boolean after(Date date)
boolean before(Date date)
新版JDK8之时间日期处理类
Java8通过发布新的Date-Time API(JSR310)来进一步加强对日期与时间的处理 新增了很多常见的api,如日期/时间的比较,加减,格式化等 包所在位置 java.time 核心类
LocalDate:不包含具体时间的日期。
LocalTime:不含日期的时间。
LocalDateTime:包含了日期及时间。
LocalDate today= LocalDate. now();
system. out. print1n("今天日期:" + today);
system. out. print1n("现在是哪年:" + today. getYear());
system. out. print1n("现在是哪月:" + today. getMonth());
System. out. print1n("现在是哪月(数字):" + today. getMonthValue());
System. out. print1n("现在是几号:" + today. getDayofMonth());
system. out. print1n("现在是周几:" + today. getDayofweek());
system. out. print1n("加后是哪年:" + changeDate. getYear());
System. out. print1n("旧的是哪年:" + today. getYear());
system. out. print1n("isafter:" + changeDate. isAfter(today));
新版JDK8之时间日期格式化
为什么要时间日期做格式化
程序打印,或者网页显示时间日期格式,用户有不同的需求,则需要根据一定的规则进行格式化 常用的占位符
JDK8之后:引入线程安全的日期与时
LocalDateTime ldt = LocalDateTime. now ( ) ;
System. out. println ( ldt) ;
DateTimeFormatter dtf = DateTimeFormatter. ofPattern ( "yyyy- MM- dd
HH: mm: ss") ;
String ldtStr = dtf. format ( ldt) ;
System. out. println ( ldtStr) ;
获取指定的日期时间对象LocalDate Time ldt=LocalDate Time.of(2020,11,11,8,20,30);System.out.println(ldt); 计算日期时间差 java.time.Duration
LocalDateTime today = LocalDateTime. now ( ) ;
System. out. println ( today) ;
LocalDateTime changeDate = LocalDateTime. of ( 2020 , 10 , 1 , 10 , 40 , 30 ) ;
System. out. println ( changeDate) ;
Duration duration = Duration. between ( today, changeDate) ;
个参数
System. out. println ( duration. toDays ( ) ) ;
System. out. println ( duration. toHours ( ) ) ;
System. out. println ( duration. toMinutes ( ) ) ;
System. out. println ( duration. toMillis ( ) ) ;
System. out. println ( duration. toNanos ( ) ) ;