day04——常用API
一、 StringBuilder类
StringBuilder代表可变字符串对象 ,相当于是一个容器,它里面的字符串是可以改变的,就是用来操作字符串的。
好处:StringBuilder比String更合适做字符串的修改操作,效率更高,代码也更加简洁。
1.1 StringBuilder方法演示
接下来我们用代码演示一下StringBuilder的用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class Test { public static void main (String[] args) { StringBuilder sb = new StringBuilder ("itehima" ); sb.append(12 ); sb.append("黑马" ); sb.append(true ); sb.append(666 ).append("黑马2" ).append(666 ); System.out.println(sb); sb.reverse(); System.out.println(sb); System.out.println(sb.length()); String s = sb.toString(); System.out.println(s); } }
为什么要用StringBuilder对字符串进行操作 呢?因为它的效率比String更高,我们可以下面两段代码验证一下。
经过我的验证,直接使用Stirng拼接100万次,等了1分钟,还没结束,我等不下去了;但是使用StringBuilder做拼接,不到1秒钟出结果了。
1.2 StringBuilder应用案例
接下来,我们通过一个案例把StringBuilder运用下,案例需求如下图所示
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class Test { public static void main (String[] args) { String str = getArrayData( new int []{11 ,22 ,33 }); System.out.println(str); } public static String getArrayData (int [] arr) { if (arr==null ){ return null ; } StringBuilder sb = new StringBuilder ("[" ); for (int i=0 ; i<arr.length; i++){ if (i==arr.length-1 ){ sb.append(arr[i]).append("]" );; }else { sb.append(arr[i]).append("," ); } } return sb.toString(); } }
二、StringJoiner类
接下来,我们学习一个类叫做StringJoiner,学习这个类干嘛用呢?是因为我们前面使用StringBuilder拼接字符串的时,代码写起来还是有一点麻烦,而StringJoiner号称是拼接神器,不仅效率高,而且代码简洁。StringJoiner添加时是.add() ,StringBuilder是.append()
下面演示一下StringJoiner的基本使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class Test { public static void main (String[] args) { StringJoiner s = new StringJoiner ("," ); s.add("java1" ); s.add("java2" ); s.add("java3" ); System.out.println(s); StringJoiner s1 = new StringJoiner ("," ,"[" ,"]" ); s1.add("java1" ); s1.add("java2" ); s1.add("java3" ); System.out.println(s1); } }
使用StirngJoiner改写前面把数组转换为字符串的案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Test { public static void main (String[] args) { String str = getArrayData( new int []{11 ,22 ,33 }); System.out.println(str); } public static String getArrayData (int [] arr) { if (arr==null ){ return null ; } StringJoiner s = new StringJoiner (", " ,"[" ,"]" ); for (int i=0 ; i<arr.length; i++){ s.add(String.valueOf(arr[i])); } return s.toString(); } }
三、Math类
Math是数学的意思,该类提供了很多个进行数学运算的方法,如求绝对值,求最大值,四舍五入等,话不多说,直接上代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public class MathTest { public static void main (String[] args) { System.out.println(Math.abs(-12 )); System.out.println(Math.abs(123 )); System.out.println(Math.abs(-3.14 )); System.out.println(Math.ceil(4.0000001 )); System.out.println(Math.ceil(4.0 )); System.out.println(Math.floor(4.999999 )); System.out.println(Math.floor(4.0 )); System.out.println(Math.round(3.4999 )); System.out.println(Math.round(3.50001 )); System.out.println(Math.max(10 , 20 )); System.out.println(Math.min(10 , 20 )); System.out.println(Math.pow(2 , 3 )); System.out.println(Math.pow(3 , 2 )); System.out.println(Math.random()); } }
四、 System类
接下来,学习一个System类,这是系统类,提供了一些获取获取系统数据 的方法。比如获取系统时间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public class SystemTest { public static void main (String[] args) { System.exit(0 ); long time = System.currentTimeMillis(); System.out.println(time); for (int i = 0 ; i < 1000000 ; i++) { System.out.println("输出了:" + i); } long time2 = System.currentTimeMillis(); System.out.println((time2 - time) / 1000.0 + "s" ); } }
五、Runtime类
接下来,我们再学习一个Java的运行时类,叫Runtime类。这个类可以用来获取JVM的一些信息 ,也可以用这个类去执行其他的程序。话不多少,上代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class RuntimeTest { public static void main (String[] args) throws IOException, InterruptedException { Runtime r = Runtime.getRuntime(); System.out.println(r.availableProcessors()); System.out.println(r.totalMemory()/1024.0 /1024.0 + "MB" ); System.out.println(r.freeMemory()/1024.0 /1024.0 + "MB" ); Process p = r.exec("QQ" ); Thread.sleep(5000 ); p.destroy(); } }
六、BigDecimal类
接下来我们学习的这个类叫BigDecimal。观察下面代码,看这个代码有什么问题?再说BigDeimal这个类是干什么用的,这样会更好理解一些。
1 2 3 4 5 6 7 8 public class Test { public static void main (String[] args) { System.out.println(0.1 + 0.2 ); System.out.println(1.0 - 0.32 ); System.out.println(1.015 * 100 ); System.out.println(1.301 / 100 ); } }
运行以上代码,我们会发现,结果并和我们想看到的不太一样。如下图所示
为了解决计算精度损失 的问题,Java给我们提供了BigDecimal类,它提供了一些方法可以对数据进行四则运算,而且不丢失精度,同时还可以保留指定的小数位。下面看代码,演示一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 public class Test2 { public static void main (String[] args) { double a = 0.1 ; double b = 0.2 ; BigDecimal a1 = BigDecimal.valueOf(a); BigDecimal b1 = BigDecimal.valueOf(b); BigDecimal c1 = a1.add(b1); System.out.println(c1); BigDecimal c2 = a1.subtract(b1); System.out.println(c2); BigDecimal c3 = a1.multiply(b1); System.out.println(c3); BigDecimal c4 = a1.divide(b1); System.out.println(c4); BigDecimal d1 = BigDecimal.valueOf(0.1 ); BigDecimal d2 = BigDecimal.valueOf(0.3 ); BigDecimal d3 = d1.divide(d2, 2 , RoundingMode.HALF_UP); System.out.println(d3); double db1 = d3.doubleValue(); double db2 = c1.doubleValue(); print(db1); print(db2); } public static void print (double a) { System.out.println(a); } }
五、Date类
接下来,我们学习一下Date类,Java中是由这个类的对象用来表示日期或者时间。
Date对象记录的时间是用毫秒值来表示的。Java语言规定,1970年1月1日0时0分0秒认为是时间的起点,此时记作0,那么1000(1秒=1000毫秒)就表示1970年1月1日0时0分1秒,依次内推。
下面是Date类的构造方法,和常见的成员方法,利用这些API写代码尝试一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Test1Date { public static void main (String[] args) { Date d = new Date (); System.out.println(d); long time = d.getTime(); System.out.println(time); time += 2 * 1000 ; Date d2 = new Date (time); System.out.println(d2); Date d3 = new Date (); d3.setTime(time); System.out.println(d3); } }
各位同学,前面我们打印Date对象时,发现打印输出的日期格式我们并不喜欢,是不是?你们喜欢那种格式呢?是不是像下面页面中这种格式啊?接下来我们学习的SimpleDateFormat类就可以转换Date对象表示日期时间的显示格式。
接下来,我们先演示一下日期格式化,需要用到如下的几个方法
注意:创建SimpleDateFormat对象时,在构造方法的参数位置传递日期格式,而日期格式是由一些特定的字母拼接而来的。我们需要记住常用的几种日期/时间格式
1 2 3 4 5 6 7 8 9 10 11 12 字母 表示含义 yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒 SSS 毫秒 "2022年12月12日" 的格式是 "yyyy年MM月dd日" "2022-12-12 12:12:12" 的格式是 "yyyy-MM-dd HH:mm:ss" 按照上面的格式可以任意拼接,但是字母不能写错
最后,上代码演示一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public class Test2SimpleDateFormat { public static void main (String[] args) throws ParseException { Date d = new Date (); System.out.println(d); long time = d.getTime(); System.out.println(time); SimpleDateFormat sdf = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss EEE a" ); String rs = sdf.format(d); String rs2 = sdf.format(time); System.out.println(rs); System.out.println(rs2); System.out.println("----------------------------------------------" ); String dateStr = "2022-12-12 12:12:11" ; SimpleDateFormat sdf2 = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss" ); Date d2 = sdf2.parse(dateStr); System.out.println(d2); } }
日期格式化&解析案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 public class Test3 { public static void main (String[] args) throws ParseException { String start = "2023年11月11日 0:0:0" ; String end = "2023年11月11日 0:10:0" ; String xj = "2023年11月11日 0:01:18" ; String xp = "2023年11月11日 0:10:57" ; SimpleDateFormat sdf = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss" ); Date startDt = sdf.parse(start); Date endDt = sdf.parse(end); Date xjDt = sdf.parse(xj); Date xpDt = sdf.parse(xp); long startTime = startDt.getTime(); long endTime = endDt.getTime(); long xjTime = xjDt.getTime(); long xpTime = xpDt.getTime(); if (xjTime >= startTime && xjTime <= endTime){ System.out.println("小贾您秒杀成功了~~" ); }else { System.out.println("小贾您秒杀失败了~~" ); } if (xpTime >= startTime && xpTime <= endTime){ System.out.println("小皮您秒杀成功了~~" ); }else { System.out.println("小皮您秒杀失败了~~" ); } } }
七、Calendar类
学完Date类和SimpleDateFormat类之后,我们再学习一个和日期相关的类,它是Calendar类。Calendar类表示日历,它提供了一些比Date类更好用的方法。
比如下面的案例,用Date类就不太好做,而用Calendar就特别方便。因为Calendar类提供了方法可以直接对日历中的年、月、日、时、分、秒等进行运算。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 public class Test4Calendar { public static void main (String[] args) { Calendar now = Calendar.getInstance(); System.out.println(now); int year = now.get(Calendar.YEAR); System.out.println(year); int days = now.get(Calendar.DAY_OF_YEAR); System.out.println(days); Date d = now.getTime(); System.out.println(d); long time = now.getTimeInMillis(); System.out.println(time); now.set(Calendar.MONTH, 9 ); now.set(Calendar.DAY_OF_YEAR, 125 ); System.out.println(now); now.add(Calendar.DAY_OF_YEAR, 100 ); now.add(Calendar.DAY_OF_YEAR, -10 ); now.add(Calendar.DAY_OF_MONTH, 6 ); now.add(Calendar.HOUR, 12 ); now.set(2026 , 11 , 22 ); System.out.println(now); } }
八、为什么JDK8要新增日期类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class Test { public static void main (String[] args) { Date d = new Date (); Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); System.out.println(year); } }
九、JDK8日期、时间、日期时间
接下来,我们学习一下JDK8新增的日期类。为什么以前的Date类就可以表示日期,为什么要有新增的日期类呢?原因如下
JDK8新增的日期类分得更细致一些,比如表示年月日用LocalDate类 、表示时分秒用LocalTime类 、而表示年月日时分秒用LocalDateTime类 等;除了这些类还提供了对时区、时间间隔进行操作的类等。它们几乎把对日期/时间的所有操作都通过了API方法,用起来特别方便。
先学习表示日期、时间、日期时间的类;有LocalDate、LocalTime、以及LocalDateTime类。仔细阅读代码,你会发现这三个类的用法套路都是一样的。
LocalDate类的基本使用
星期几
int dayOfWeek = ld.getDayOfWeek().getValue();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 public class Test1_LocalDate { public static void main (String[] args) { LocalDate ld = LocalDate.now(); System.out.println(ld); int year = ld.getYear(); int month = ld.getMonthValue(); int day = ld.getDayOfMonth(); int dayOfYear = ld.getDayOfYear(); int dayOfWeek = ld.getDayOfWeek().getValue(); System.out.println(year); System.out.println(day); System.out.println(dayOfWeek); LocalDate ld2 = ld.withYear(2099 ); LocalDate ld3 = ld.withMonth(12 ); System.out.println(ld2); System.out.println(ld3); System.out.println(ld); LocalDate ld4 = ld.plusYears(2 ); LocalDate ld5 = ld.plusMonths(2 ); LocalDate ld6 = ld.minusYears(2 ); LocalDate ld7 = ld.minusMonths(2 ); LocalDate ld8 = LocalDate.of(2099 , 12 , 12 ); LocalDate ld9 = LocalDate.of(2099 , 12 , 12 ); System.out.println(ld8.equals(ld9)); System.out.println(ld8.isAfter(ld)); System.out.println(ld8.isBefore(ld)); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 public class Test2_LocalTime { public static void main (String[] args) { LocalTime lt = LocalTime.now(); System.out.println(lt); int hour = lt.getHour(); int minute = lt.getMinute(); int second = lt.getSecond(); int nano = lt.getNano(); LocalTime lt3 = lt.withHour(10 ); LocalTime lt4 = lt.withMinute(10 ); LocalTime lt5 = lt.withSecond(10 ); LocalTime lt6 = lt.withNano(10 ); LocalTime lt7 = lt.plusHours(10 ); LocalTime lt8 = lt.plusMinutes(10 ); LocalTime lt9 = lt.plusSeconds(10 ); LocalTime lt10 = lt.plusNanos(10 ); LocalTime lt11 = lt.minusHours(10 ); LocalTime lt12 = lt.minusMinutes(10 ); LocalTime lt13 = lt.minusSeconds(10 ); LocalTime lt14 = lt.minusNanos(10 ); LocalTime lt15 = LocalTime.of(12 , 12 , 12 ); LocalTime lt16 = LocalTime.of(12 , 12 , 12 ); System.out.println(lt15.equals(lt16)); System.out.println(lt15.isAfter(lt)); System.out.println(lt15.isBefore(lt)); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 public class Test3_LocalDateTime { public static void main (String[] args) { LocalDateTime ldt = LocalDateTime.now(); System.out.println(ldt); int year = ldt.getYear(); int month = ldt.getMonthValue(); int day = ldt.getDayOfMonth(); int dayOfYear = ldt.getDayOfYear(); int dayOfWeek = ldt.getDayOfWeek().getValue(); int hour = ldt.getHour(); int minute = ldt.getMinute(); int second = ldt.getSecond(); int nano = ldt.getNano(); LocalDateTime ldt2 = ldt.withYear(2029 ); LocalDateTime ldt3 = ldt.withMinute(59 ); LocalDateTime ldt4 = ldt.plusYears(2 ); LocalDateTime ldt5 = ldt.plusMinutes(3 ); LocalDateTime ldt6 = ldt.minusYears(2 ); LocalDateTime ldt7 = ldt.minusMinutes(3 ); LocalDateTime ldt8 = LocalDateTime.of(2029 , 12 , 12 , 12 , 12 , 12 , 1222 ); LocalDateTime ldt9 = LocalDateTime.of(2029 , 12 , 12 , 12 , 12 , 12 , 1222 ); System.out.println(ldt9.equals(ldt8)); System.out.println(ldt9.isAfter(ldt)); System.out.println(ldt9.isBefore(ldt)); LocalDate ld = ldt.toLocalDate(); LocalTime lt = ldt.toLocalTime(); LocalDateTime ldt10 = LocalDateTime.of(ld, lt); } }
十、JDK8日期(时区)
接着,我们学习代表时区的两个类。由于世界各个国家与地区的经度不同,各地区的时间也有所不同,因此会划分为不同的时区。每一个时区的时间也不太一样。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 public class Test4_ZoneId_ZonedDateTime { public static void main (String[] args) { ZoneId zoneId = ZoneId.systemDefault(); System.out.println(zoneId.getId()); System.out.println(zoneId); System.out.println(ZoneId.getAvailableZoneIds()); ZoneId zoneId1 = ZoneId.of("America/New_York" ); ZonedDateTime now = ZonedDateTime.now(zoneId1); System.out.println(now); ZonedDateTime now1 = ZonedDateTime.now(Clock.systemUTC()); System.out.println(now1); ZonedDateTime now2 = ZonedDateTime.now(); System.out.println(now2); } }
十一、JDK8日期(Instant类)
接下来,我们来学习Instant这个类。通过获取Instant的对象可以拿到此刻的时间,该时间由两部分组成:从1970-01-01
00:00:00 开始走到此刻的总秒数+不够1秒的纳秒数。
该类提供的方法如下图所示,可以用来获取当前时间,也可以对时间进行加、减、获取等操作。
作用:可以用来记录代码的执行时间,或用于记录用户操作某个事件的时间点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class Test5_Instant { public static void main (String[] args) { Instant now = Instant.now(); long second = now.getEpochSecond(); System.out.println(second); int nano = now.getNano(); System.out.println(nano); System.out.println(now); Instant instant = now.plusNanos(111 ); Instant now1 = Instant.now(); Instant now2 = Instant.now(); LocalDateTime l = LocalDateTime.now(); } }
十二、JDK8日期(格式化器)
接下来,我们学习一个新增的日期格式化类,叫DateTimeFormater。它可以从来对日期进行格式化和解析。它代替了原来的SimpleDateFormat类。
需要用到的方法,如下图所示
接下来,将上面的方法用代码来演示一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class Test6_DateTimeFormatter { public static void main (String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss" ); LocalDateTime now = LocalDateTime.now(); System.out.println(now); String rs = formatter.format(now); System.out.println(rs); String rs2 = now.format(formatter); System.out.println(rs2); String dateStr = "2029年12月12日 12:12:11" ; LocalDateTime ldt = LocalDateTime.parse(dateStr, formatter); System.out.println(ldt); } }
十三、JDK8日期(Period类)
除以了上新增的类,JDK8还补充了两个类,一个叫Period类、一个叫Duration类;这两个类可以用来计算两个时间点的时间间隔 。
其中Period用来计算日期间隔(年、月、日),Duration用来计算时间间隔(时、分、秒、纳秒)
先来演示Period类的用法,它的方法如下图所示。可以用来计算两个日期之间相隔的年、相隔的月、相隔的日。只能两个计算LocalDate对象之间的间隔
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Test7_Period { public static void main (String[] args) { LocalDate start = LocalDate.of(2029 , 8 , 10 ); LocalDate end = LocalDate.of(2029 , 12 , 15 ); Period period = Period.between(start, end); System.out.println(period.getYears()); System.out.println(period.getMonths()); System.out.println(period.getDays()); } }
十四、JDK8日期(Duration类)
接下来,我们学习Duration类。它是用来表示两个时间对象的时间间隔。可以用于计算两个时间对象相差的天数、小时数、分数、秒数、纳秒数;支持LocalTime、LocalDateTime、Instant等时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Test8_Duration { public static void main (String[] args) { LocalDateTime start = LocalDateTime.of(2025 , 11 , 11 , 11 , 10 , 10 ); LocalDateTime end = LocalDateTime.of(2025 , 11 , 11 , 11 , 11 , 11 ); Duration duration = Duration.between(start, end); System.out.println(duration.toDays()); System.out.println(duration.toHours()); System.out.println(duration.toMinutes()); System.out.println(duration.toSeconds()); System.out.println(duration.toMillis()); System.out.println(duration.toNanos()); } }