时间类
Date类
Date类中的多数方法已经过时,常用的方法有:
- public long getTime() 把日期对象转换成对应的时间毫秒值。
 public void setTime(long time) 把方法参数给定的毫秒值设置给日期对象
public class DateDemo02 {public static void main(String[] args) {//创建日期对象Date d = new Date();//public long getTime():获取的是日期对象从1970年1月1日 00:00:00到现在的毫秒值//System.out.println(d.getTime());//System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");//public void setTime(long time):设置时间,给的是毫秒值//long time = 1000*60*60;long time = System.currentTimeMillis();d.setTime(time);System.out.println(d);}}
小结:Date表示特定的时间瞬间,我们可以使用Date对象对时间进行操作。
SimpleDateFormat类
格式规则
常用的格式规则为:
| 标识字母(区分大小写) | 含义 | 
|---|---|
| y | 年 | 
| M | 月 | 
| d | 日 | 
| H | 时 | 
| m | 分 | 
| s | 秒 | 
备注:更详细的格式规则,可以参考SimpleDateFormat类的API文档。
- public String format(Date date):将Date对象格式化为字符串。
 - public Date parse(String source):将字符串解析为Date对象。 ```java
 
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;
public class A03_SimpleDateFormatDemo1 { public static void main(String[] args) throws ParseException { / public simpleDateFormat() 默认格式 public simpleDateFormat(String pattern) 指定格式 public final string format(Date date) 格式化(日期对象 ->字符串) public Date parse(string source) 解析(字符串 ->日期对象) /
//1.定义一个字符串表示时间String str = "2023-11-11 11:11:11";//2.利用空参构造创建simpleDateFormat对象// 细节://创建对象的格式要跟字符串的格式完全一致SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date = sdf.parse(str);//3.打印结果System.out.println(date.getTime());//1699672271000}private static void method1() {//1.利用空参构造创建simpleDateFormat对象,默认格式SimpleDateFormat sdf1 = new SimpleDateFormat();Date d1 = new Date(0L);String str1 = sdf1.format(d1);System.out.println(str1);//1970/1/1 上午8:00//2.利用带参构造创建simpleDateFormat对象,指定格式SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");String str2 = sdf2.format(d1);System.out.println(str2);//1970年01月01日 08:00:00//课堂练习:yyyy年MM月dd日 时:分:秒 星期}
}
> **小结:DateFormat可以将Date对象和字符串相互转换。**<a name="yHKFc"></a>### Calendar类**常用方法**| **方法名** | **说明** || --- | --- || public static Calendar getInstance() | 获取一个它的子类GregorianCalendar对象。 || public int get(int field) | 获取某个字段的值。field参数表示获取哪个字段的值,可以使用Calender中定义的常量来表示:Calendar.YEAR : 年Calendar.MONTH :月Calendar.DAY_OF_MONTH:月中的日期Calendar.HOUR:小时Calendar.MINUTE:分钟Calendar.SECOND:秒Calendar.DAY_OF_WEEK:星期 || public void set(int field,int value) | 设置某个字段的值 || public void add(int field,int amount) | 为某个字段增加/减少指定的值 |<a name="QF0Qi"></a>#### get方法示例```javapublic class Demo {public static void main(String[] args) {//1.获取一个GregorianCalendar对象Calendar instance = Calendar.getInstance();//获取子类对象//2.打印子类对象System.out.println(instance);//3.获取属性int year = instance.get(Calendar.YEAR);int month = instance.get(Calendar.MONTH) + 1;//Calendar的月份值是0-11int day = instance.get(Calendar.DAY_OF_MONTH);int hour = instance.get(Calendar.HOUR);int minute = instance.get(Calendar.MINUTE);int second = instance.get(Calendar.SECOND);int week = instance.get(Calendar.DAY_OF_WEEK);//返回值范围:1--7,分别表示:"星期日","星期一","星期二",...,"星期六"System.out.println(year + "年" + month + "月" + day + "日" +hour + ":" + minute + ":" + second);System.out.println(getWeek(week));}//查表法,查询星期几public static String getWeek(int w) {//w = 1 --- 7//做一个表(数组)String[] weekArray = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};// 索引 [0] [1] [2] [3] [4] [5] [6]//查表return weekArray[w - 1];}}
set方法示例
public class Demo {public static void main(String[] args) {//设置属性——set(int field,int value):Calendar c1 = Calendar.getInstance();//获取当前日期//计算班长出生那天是星期几(假如班长出生日期为:1998年3月18日)c1.set(Calendar.YEAR, 1998);c1.set(Calendar.MONTH, 3 - 1);//转换为Calendar内部的月份值c1.set(Calendar.DAY_OF_MONTH, 18);int w = c1.get(Calendar.DAY_OF_WEEK);System.out.println("班长出生那天是:" + getWeek(w));}//查表法,查询星期几public static String getWeek(int w) {//w = 1 --- 7//做一个表(数组)String[] weekArray = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};// 索引 [0] [1] [2] [3] [4] [5] [6]//查表return weekArray[w - 1];}}
add方法示例
public class Demo {public static void main(String[] args) {//计算200天以后是哪年哪月哪日,星期几?Calendar c2 = Calendar.getInstance();//获取当前日期c2.add(Calendar.DAY_OF_MONTH, 200);//日期加200int y = c2.get(Calendar.YEAR);int m = c2.get(Calendar.MONTH) + 1;//转换为实际的月份int d = c2.get(Calendar.DAY_OF_MONTH);int wk = c2.get(Calendar.DAY_OF_WEEK);System.out.println("200天后是:" + y + "年" + m + "月" + d + "日" + getWeek(wk));}//查表法,查询星期几public static String getWeek(int w) {//w = 1 --- 7//做一个表(数组)String[] weekArray = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};// 索引 [0] [1] [2] [3] [4] [5] [6]//查表return weekArray[w - 1];}}
JDK8时间相关类
| JDK8时间类类名 | 作用 | 
|---|---|
| ZoneId | 时区 | 
| Instant | 时间戳 | 
| ZoneDateTime | 带时区的时间 | 
| DateTimeFormatter | 用于时间的格式化和解析 | 
| LocalDate | 年、月、日 | 
| LocalTime | 时、分、秒 | 
| LocalDateTime | 年、月、日、时、分、秒 | 
| Duration | 时间间隔(秒,纳,秒) | 
| Period | 时间间隔(年,月,日) | 
| ChronoUnit | 时间间隔(所有单位) | 
ZoneId 时区
/*static Set<string> getAvailableZoneIds() 获取Java中支持的所有时区static ZoneId systemDefault() 获取系统默认时区static Zoneld of(string zoneld) 获取一个指定时区*///1.获取所有的时区名称Set<String> zoneIds = ZoneId.getAvailableZoneIds();System.out.println(zoneIds.size());//600System.out.println(zoneIds);// Asia/Shanghai//2.获取当前系统的默认时区ZoneId zoneId = ZoneId.systemDefault();System.out.println(zoneId);//Asia/Shanghai//3.获取指定的时区ZoneId zoneId1 = ZoneId.of("Asia/Pontianak");System.out.println(zoneId1);//Asia/Pontianak
Instant 时间戳
/*static Instant now() 获取当前时间的Instant对象(标准时间)static Instant ofXxxx(long epochMilli) 根据(秒/毫秒/纳秒)获取Instant对象ZonedDateTime atZone(ZoneIdzone) 指定时区boolean isxxx(Instant otherInstant) 判断系列的方法Instant minusXxx(long millisToSubtract) 减少时间系列的方法Instant plusXxx(long millisToSubtract) 增加时间系列的方法*///1.获取当前时间的Instant对象(标准时间)Instant now = Instant.now();System.out.println(now);//2.根据(秒/毫秒/纳秒)获取Instant对象Instant instant1 = Instant.ofEpochMilli(0L);System.out.println(instant1);//1970-01-01T00:00:00zInstant instant2 = Instant.ofEpochSecond(1L);System.out.println(instant2);//1970-01-01T00:00:01ZInstant instant3 = Instant.ofEpochSecond(1L, 1000000000L);System.out.println(instant3);//1970-01-01T00:00:027//3. 指定时区ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));System.out.println(time);//4.isXxx 判断Instant instant4=Instant.ofEpochMilli(0L);Instant instant5 =Instant.ofEpochMilli(1000L);//5.用于时间的判断//isBefore:判断调用者代表的时间是否在参数表示时间的前面boolean result1=instant4.isBefore(instant5);System.out.println(result1);//true//isAfter:判断调用者代表的时间是否在参数表示时间的后面boolean result2 = instant4.isAfter(instant5);System.out.println(result2);//false//6.Instant minusXxx(long millisToSubtract) 减少时间系列的方法Instant instant6 =Instant.ofEpochMilli(3000L);System.out.println(instant6);//1970-01-01T00:00:03ZInstant instant7 =instant6.minusSeconds(1);System.out.println(instant7);//1970-01-01T00:00:02Z
ZoneDateTime 带时区的时间
/*static ZonedDateTime now() 获取当前时间的ZonedDateTime对象static ZonedDateTime ofXxxx(。。。) 获取指定时间的ZonedDateTime对象ZonedDateTime withXxx(时间) 修改时间系列的方法ZonedDateTime minusXxx(时间) 减少时间系列的方法ZonedDateTime plusXxx(时间) 增加时间系列的方法*///1.获取当前时间对象(带时区)ZonedDateTime now = ZonedDateTime.now();System.out.println(now);//2.获取指定的时间对象(带时区)1/年月日时分秒纳秒方式指定ZonedDateTime time1 = ZonedDateTime.of(2023, 10, 1,11, 12, 12, 0, ZoneId.of("Asia/Shanghai"));System.out.println(time1);//通过Instant + 时区的方式指定获取时间对象Instant instant = Instant.ofEpochMilli(0L);ZoneId zoneId = ZoneId.of("Asia/Shanghai");ZonedDateTime time2 = ZonedDateTime.ofInstant(instant, zoneId);System.out.println(time2);//3.withXxx 修改时间系列的方法ZonedDateTime time3 = time2.withYear(2000);System.out.println(time3);//4. 减少时间ZonedDateTime time4 = time3.minusYears(1);System.out.println(time4);//5.增加时间ZonedDateTime time5 = time4.plusYears(1);System.out.println(time5);
DateTimeFormatter 用于时间的格式化和解析
/*static DateTimeFormatter ofPattern(格式) 获取格式对象String format(时间对象) 按照指定方式格式化*///获取时间对象ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));// 解析/格式化器DateTimeFormatter dtf1=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm;ss EE a");// 格式化System.out.println(dtf1.format(time));
LocalDate 年、月、日
//1.获取当前时间的日历对象(包含 年月日)LocalDate nowDate = LocalDate.now();//System.out.println("今天的日期:" + nowDate);//2.获取指定的时间的日历对象LocalDate ldDate = LocalDate.of(2023, 1, 1);System.out.println("指定日期:" + ldDate);System.out.println("=============================");//3.get系列方法获取日历中的每一个属性值//获取年int year = ldDate.getYear();System.out.println("year: " + year);//获取月//方式一:Month m = ldDate.getMonth();System.out.println(m);System.out.println(m.getValue());//方式二:int month = ldDate.getMonthValue();System.out.println("month: " + month);//获取日int day = ldDate.getDayOfMonth();System.out.println("day:" + day);//获取一年的第几天int dayofYear = ldDate.getDayOfYear();System.out.println("dayOfYear:" + dayofYear);//获取星期DayOfWeek dayOfWeek = ldDate.getDayOfWeek();System.out.println(dayOfWeek);System.out.println(dayOfWeek.getValue());//is开头的方法表示判断System.out.println(ldDate.isBefore(ldDate));System.out.println(ldDate.isAfter(ldDate));//with开头的方法表示修改,只能修改年月日LocalDate withLocalDate = ldDate.withYear(2000);System.out.println(withLocalDate);//minus开头的方法表示减少,只能减少年月日LocalDate minusLocalDate = ldDate.minusYears(1);System.out.println(minusLocalDate);//plus开头的方法表示增加,只能增加年月日LocalDate plusLocalDate = ldDate.plusDays(1);System.out.println(plusLocalDate);//-------------// 判断今天是否是你的生日LocalDate birDate = LocalDate.of(2000, 1, 1);LocalDate nowDate1 = LocalDate.now();MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());MonthDay nowMd = MonthDay.from(nowDate1);System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));//今天是你的生日吗?
LocalTime 时、分、秒
// 获取本地时间的日历对象。(包含 时分秒)LocalTime nowTime = LocalTime.now();System.out.println("今天的时间:" + nowTime);int hour = nowTime.getHour();//时System.out.println("hour: " + hour);int minute = nowTime.getMinute();//分System.out.println("minute: " + minute);int second = nowTime.getSecond();//秒System.out.println("second:" + second);int nano = nowTime.getNano();//纳秒System.out.println("nano:" + nano);System.out.println("------------------------------------");System.out.println(LocalTime.of(8, 20));//时分System.out.println(LocalTime.of(8, 20, 30));//时分秒System.out.println(LocalTime.of(8, 20, 30, 150));//时分秒纳秒LocalTime mTime = LocalTime.of(8, 20, 30, 150);//is系列的方法System.out.println(nowTime.isBefore(mTime));System.out.println(nowTime.isAfter(mTime));//with系列的方法,只能修改时、分、秒System.out.println(nowTime.withHour(10));//plus系列的方法,只能修改时、分、秒System.out.println(nowTime.plusHours(10));
LocalDateTime 年、月、日、时、分、秒
// 当前时间的的日历对象(包含年月日时分秒)LocalDateTime nowDateTime = LocalDateTime.now();System.out.println("今天是:" + nowDateTime);//今天是:System.out.println(nowDateTime.getYear());//年System.out.println(nowDateTime.getMonthValue());//月System.out.println(nowDateTime.getDayOfMonth());//日System.out.println(nowDateTime.getHour());//时System.out.println(nowDateTime.getMinute());//分System.out.println(nowDateTime.getSecond());//秒System.out.println(nowDateTime.getNano());//纳秒// 日:当年的第几天System.out.println("dayofYear:" + nowDateTime.getDayOfYear());//星期System.out.println(nowDateTime.getDayOfWeek());System.out.println(nowDateTime.getDayOfWeek().getValue());//月份System.out.println(nowDateTime.getMonth());System.out.println(nowDateTime.getMonth().getValue());LocalDate ld = nowDateTime.toLocalDate();System.out.println(ld);LocalTime lt = nowDateTime.toLocalTime();System.out.println(lt.getHour());System.out.println(lt.getMinute());System.out.println(lt.getSecond());
Duration 时间间隔(秒,纳,秒)
// 本地日期时间对象。LocalDateTime today = LocalDateTime.now();System.out.println(today);// 出生的日期时间对象LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1, 0, 0, 0);System.out.println(birthDate);Duration duration = Duration.between(birthDate, today);//第二个参数减第一个参数System.out.println("相差的时间间隔对象:" + duration);System.out.println("============================================");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());//两个时间差的纳秒数
Period 时间间隔(年,月,日)
// 当前本地 年月日LocalDate today = LocalDate.now();System.out.println(today);// 生日的 年月日LocalDate birthDate = LocalDate.of(2000, 1, 1);System.out.println(birthDate);Period period = Period.between(birthDate, today);//第二个参数减第一个参数System.out.println("相差的时间间隔对象:" + period);System.out.println(period.getYears());System.out.println(period.getMonths());System.out.println(period.getDays());System.out.println(period.toTotalMonths());
ChronoUnit 时间间隔(所有单位)
// 当前时间LocalDateTime today = LocalDateTime.now();System.out.println(today);// 生日时间LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1,0, 0, 0);System.out.println(birthDate);System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today));System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today));System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today));System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today));System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today));System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today));System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today));System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today));System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today));System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today));System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today));System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today));System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today));System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today));System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));
包装类
这八种基本类型都有对应的包装类分别为:Byte、Short、Integer、Long、Float、Double、Boolean 、Character。
Integer的默认值是null; int的默认值是0。
基本类型都有对应的包装类型,基本类型与其对应的包装类型之间的赋值使用自动装箱与拆箱完成。
Integer x = 2; // 装箱 调用了 Integer.valueOf(2)int y = x; // 拆箱 调用了 X.intValue()
自动装箱演示:
//考虑以下代码:List<Integer> li = new ArrayList<>();for (int i = 1; i < 50; i += 2)li.add(i);//实际上是:List<Integer> li = new ArrayList<>();for (int i = 1; i < 50; i += 2)li.add(Integer.valueOf(i));
自动拆箱演示:
//考虑以下方法:public static int sumEven(List<Integer> li) {int sum = 0;for (Integer i: li)if (i % 2 == 0)sum += i;return sum;}//实际上是:public static int sumEven(List<Integer> li) {int sum = 0;for (Integer i : li)if (i.intValue() % 2 == 0)sum += i.intValue();return sum;}
Integer.parseInt()
重点方法:
static  int  parseInt(String s)     
静态方法,传参String,返回int
int retValue=Integer.parseInt("123")System.out.println(retValue+100);
(面试)手写一个Integer.parseInt()方法
public class Demo {public static void main(String[] args) {int num = parseInt("123456");System.out.println(num);}public static int parseInt(String str) {//声明一个字符数组char[] chars = new char[str.length()];//声明一个整型数组(用来装字符转换成整型数字结果)int[] ints = new int[str.length()];for (int i = 0; i < str.length(); i++) {//分解字符串,装入字符数组chars[i] = str.charAt(i);//把字符数组里的字符通过-'0'转换成整型数字,装入整型数组ints[i] = chars[i] - '0';}//把整型数组转换成整型int num = 0;for (int i = 0; i < ints.length; i++) {num = num * 10 + ints[i];}return num;}}
缓存池
new Integer(123) 与 Integer.valueOf(123) 的区别在于:
- new Integer(123) 每次都会新建一个对象;
 - Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用。
valueOf() 方法的实现比较简单,就是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。Integer x = new Integer(123);Integer y = new Integer(123);System.out.println(x == y); // falseInteger z = Integer.valueOf(123);Integer k = Integer.valueOf(123);System.out.println(z == k); // true
在 Java 8 中,Integer 缓存池的大小默认为 -128~127。 ```java static final int low = -128;////缓存下届,不可改变了,只有上届可以改变 static final int high; static final Integer cache[];public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}
 
static { // high value may be configured by property int h = 127;/h值,可以通过设置jdk的AutoBoxCacheMax参数调整(以下有解释), 自动缓存区间设置为[-128,N]。注意区间的下界是固定 / String integerCacheHighPropValue = sun.misc.VM.getSavedProperty(“java.lang.Integer.IntegerCache.high”); if (integerCacheHighPropValue != null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127);//取较大的作为上界 //但要注意不能比Integer的边界MAX_VALUE大 // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h;
cache = new Integer[(high - low) + 1];int j = low;for(int k = 0; k < cache.length; k++)cache[k] = new Integer(j++);// range [-128, 127] must be interned (JLS7 5.1.7)assert IntegerCache.high >= 127;
}
编译器会在自动装箱过程调用 valueOf() 方法,因此多个值相同且值在缓存池范围内的 Integer 实例使用自动装箱来创建,那么就会引用相同的对象。```javaInteger m = 123;Integer n = 123;System.out.println(m == n); // true
基本类型对应的缓冲池如下:
- boolean values true and false
 - all byte values
 - short values between -128 and 127
 - int values between -128 and 127
 - char in the range \u0000 to \u007F
 
在使用这些基本类型对应的包装类型时,如果该数值范围在缓冲池范围内,就可以直接使用缓冲池中的对象。
在 jdk 1.8 所有的数值类缓冲池中,Integer 的缓冲池 IntegerCache 很特殊,这个缓冲池的下界是 - 128,上界默认是 127,但是这个上界是可调的,在启动 jvm 的时候,通过 -XX:AutoBoxCacheMax=
注意:float和double 是没有缓存池的,每次都是new一个新的对象。
