课程:宋红康 JAVA
JDK8 之前的日期时间 API
时间戳
java.lang.System
的currentTimeMillis()
,时间戳,当前毫秒数
long time=System.currentTimeMillis()
;
System 类提供的public static long currentTimeMillis()
用来返回当前时间与 1970 年 1 月 1 日 0 时 0 分 0 秒之间以毫秒为单位的时间差。
计算世界时间的主要标准有:
- UTC(Coordinated Universal Time)
- GMT(Greenwich Mean Time )
- CST(Central Standard Time )
java.util.Date
类
- 两个构造器的使用
- 构造器一:Date():创建一个对应当前时间的 Date 对象
- 构造器二:创建指定毫秒数的 Date 对象 Date(毫秒数)
- 两个方法的使用
toString()
:显示当前的年、月、日、时、分、秒getTime()
:获取当前 Date 对象对应的毫秒数。(时间戳)
java.sql.Date
对应着数据库中的日期类型的变量
@Test
public void test2(){
//构造器一:Date():创建一个对应当前时间的Date对象
Date date1 = new Date();
System.out.println(date1.toString());//Sat Feb 16 16:35:31 GMT+08:00 2019
System.out.println(date1.getTime());//1550306204104
//构造器二:创建指定毫秒数的Date对象
Date date2 = new Date(155030620410L);
System.out.println(date2.toString());
//创建java.sql.Date对象
java.sql.Date date3 = new java.sql.Date(35235325345L);
System.out.println(date3);//1971-02-13
//如何将java.util.Date对象转换为java.sql.Date对象
//情况一:
// Date date4 = new java.sql.Date(2343243242323L);
// java.sql.Date date5 = (java.sql.Date) date4;
//情况二:
Date date6 = new Date();
java.sql.Date date7 = new java.sql.Date(date6.getTime());
}
java.text.SimpleDateFormat
SimpleDateFormat 的使用:SimpleDateFormat 对日期 Date 类的格式化和解析
格式化:日期 —>字符串—>format(date)
解析:格式化的逆过程,字符串 —> 日期—>parse(str)
@Test
public void testSimpleDateFormat() throws ParseException {
//实例化SimpleDateFormat:使用默认的构造器
SimpleDateFormat sdf = new SimpleDateFormat();
//格式化:日期 --->字符串
Date date = new Date();
System.out.println(date);
String format = sdf.format(date);
System.out.println(format);//19-12-18 上午11:43
//解析:格式化的逆过程,字符串 ---> 日期
String str = "19-12-18 上午11:43";
Date date1 = sdf.parse(str);
System.out.println(date1);
//*************按照指定的方式格式化和解析:调用带参的构造器*****************
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//格式化
String format1 = sdf1.format(date);
System.out.println(format1);//2019-02-18 11:48:27
//解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
//否则,抛异常
Date date2 = sdf1.parse("2020-02-18 11:48:27");
System.out.println(date2);
}
java.util.Calendar
(日历)类
@Test
public void testCalendar(){
//1.实例化
//方式一:创建其子类(GregorianCalendar)的对象
//方式二:调用其静态方法getInstance()
Calendar calendar = Calendar.getInstance();
//class java.util.GregorianCalendar
System.out.println(calendar.getClass());
//getTime()
Date time = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf.format(time));//2023-07-30 10:05:25
//get()
int days = calendar.get(Calendar.DAY_OF_MONTH);//获取当天是这个月的第几天
System.out.println(days);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//获取当天是这年的第几天
//set()
//calendar可变性
//把这个与的第几天设置为22号
calendar.set(Calendar.DAY_OF_MONTH,22);
//2023-07-22 10:05:25
System.out.println(sdf.format(calendar.getTime()));
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days);
//add() : 在原有日期上增减几天
calendar.add(Calendar.DAY_OF_MONTH,-3);
//2023-07-19 10:05:25
System.out.println(sdf.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH,15);
//2023-08-03 10:05:25
System.out.println(sdf.format(calendar.getTime()));
//setTime():Date ---> 日历类
Date date1 = new Date();
calendar.setTime(date1);
//2023-07-30 10:05:25
System.out.println(sdf.format(calendar.getTime()));
}
JDK 8 中新日期时间 API◐◐◐
为什么需要新的 API
- 因为之前的 API 存入如下问题:
- 可变性:像日期和时间这样的类应该是不可变的。
- 偏移性:Date 中 的年份是从 1900 开始的,而月份都从 0 开始。
- 格式化:格式化只对 Date 有用,Calendar 则不行
- 此外,它们也不是线程安全的;不能处理闰秒等。
- 新的 java.time 中包含了所有关于本地日期(LocalDate)、本地时间(LocalTime)、本地日期时间(LocalDateTime) 、时区(ZonedDate Time) 和持续时间(Duration)的类。历史悠久的 Date 类新增了 tolnstant()方法,用于把 Date 转换成新的表示形式。这些新增的本地化时间日期 API 大大简化了日期时间和本地化的管理。
LocalDate、LocalTime、LocalDateTime
@Test
public void test12(){
//now():获取当前的日期、时间、日期+时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);//2023-07-30
System.out.println(localTime);//10:32:32.785
System.out.println(localDateTime);//2023-07-30T10:32:32.785
//of():设置指定的年、月、日、时、分、秒。没有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
System.out.println(localDateTime1);//2020-10-06T13:23:43
//getXxx():获取相关的属性
System.out.println(localDateTime.getDayOfMonth());//30
System.out.println(localDateTime.getDayOfWeek());//SUNDAY
System.out.println(localDateTime.getMonth());//JULY
System.out.println(localDateTime.getMonthValue());//7
System.out.println(localDateTime.getMinute());//32
//体现不可变性: 也就是会生成一个新的对象,而原来的对象不变
//withXxx():设置相关的属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);//2023-07-30
System.out.println(localDate1);//2023-07-22
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);//2023-07-30T10:32:32.785
System.out.println(localDateTime2);//2023-07-30T04:32:32.785
//不可变性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);//2023-07-30T10:32:32.785
System.out.println(localDateTime3);//2023-10-30T10:32:32.785
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);//2023-07-30T10:32:32.785
System.out.println(localDateTime4);//2023-07-24T10:32:32.785
}
Instant
@Test
public void test2(){
//now():获取本初子午线(0°经线)对应的标准时间
Instant instant = Instant.now();
System.out.println(instant);//2023-07-30T05:32:25.143Z
//添加时间的偏移量:在现在时间的基础上+8个小时
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);//2023-07-30T13:32:25.143+08:00
//toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数 ---> Date类的getTime()
long milli = instant.toEpochMilli();
System.out.println(milli);//1690695145143
//ofEpochMilli():通过给定的毫秒数,获取Instant实例 -->Date(long millis)
Instant instant1 = Instant.ofEpochMilli(1550475314878L);//2019-02-18T07:35:14.878Z
System.out.println(instant1);
}
格式化与解析日期或时间:java.time.format.DateTimeFormatter
@Test
public void test3(){
// 方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//格式化:日期-->字符串
LocalDateTime localDateTime = LocalDateTime.now();
String str1 = formatter.format(localDateTime);
System.out.println(localDateTime);//2023-07-30T13:51:08.663
System.out.println(str1);//2023-07-30T13:51:08.663
//解析:字符串 -->日期
TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797");
System.out.println(parse);//{},ISO resolved to 2019-02-18T15:42:18.797
// 方式二:
// 本地化相关的格式。如:ofLocalizedDateTime()
// FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
//格式化
String str2 = formatter1.format(localDateTime);
System.out.println(str2);//2023年7月30日 下午01时51分08秒
// 本地化相关的格式。如:ofLocalizedDate()
// FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
//格式化
String str3 = formatter2.format(LocalDate.now());
System.out.println(str3);//2023-7-30
// 重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//格式化
String str4 = formatter3.format(LocalDateTime.now());
System.out.println(str4);//2023-07-30 01:55:14
//解析
TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09");
//{HourOfAmPm=3, NanoOfSecond=0, MinuteOfHour=52, MicroOfSecond=0, SecondOfMinute=9, MilliOfSecond=0},ISO resolved to 2019-02-18
System.out.println(accessor);
System.out.println(accessor.get(ChronoField.YEAR));//2019
System.out.println(accessor.get(ChronoField.HOUR_OF_AMPM));//3
LocalDate parse1 = formatter3.parse("2019-02-18 03:52:09", TemporalQueries.localDate());
System.out.println(parse1);//2019-02-18
LocalTime parse2 = formatter3.parse("2019-02-18 03:52:09", TemporalQueries.localTime());
System.out.println(parse2);//null
//LocalDateTime query = accessor.query(LocalDateTime::from);
//System.out.println(query);
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1909773034@qq.com