学习Java之day21

1.jdk 8之前的日期时间的API测试

  1. System类中currentTimeMillis();

  2. java.util.Date和子类java.sql.Date

  3. SimpleDateFormat

  4. Calendar

 /*
   SimpleDateFormat的使用:SimpleDateFormat对日期Date类的格式化和解析

   1.两个操作:
   1.1 格式化:日期 --->字符串
   1.2 解析:格式化的逆过程,字符串 ---> 日期

   2.SimpleDateFormat的实例化

    */
   @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);

       //解析:格式化的逆过程,字符串 ---> 日期
       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);
  }

   /*
   练习一:字符串"2020-09-08"转换为java.sql.Date

   练习二:"三天打渔两天晒网"   1990-01-01 xxxx-xx-xx 打渔?晒网?

   举例:2020-09-08 ? 总天数

   总天数 % 5 == 1,2,3 : 打渔
   总天数 % 5 == 4,0 : 晒网

   总天数的计算?
   方式一:( date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24) + 1
   方式二:1990-01-01 --> 2019-12-31 + 2020-01-01 -->2020-09-08
    */
   @Test
   public void testExer() throws ParseException {
       String birth = "2020-09-08";

       SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
       Date date = sdf1.parse(birth);
//       System.out.println(date);

       java.sql.Date birthDate = new java.sql.Date(date.getTime());
       System.out.println(birthDate);
  }


   /*
   Calendar日历类(抽象类)的使用

    */
   @Test
   public void testCalendar(){
       //1.实例化
       //方式一:创建其子类(GregorianCalendar)的对象
       //方式二:调用其静态方法getInstance()
       Calendar calendar = Calendar.getInstance();
//       System.out.println(calendar.getClass());

       //2.常用方法
       //get()
       int days = calendar.get(Calendar.DAY_OF_MONTH);
       System.out.println(days);
       System.out.println(calendar.get(Calendar.DAY_OF_YEAR));

       //set()
       //calendar可变性
       calendar.set(Calendar.DAY_OF_MONTH,22);
       days = calendar.get(Calendar.DAY_OF_MONTH);
       System.out.println(days);

       //add()
       calendar.add(Calendar.DAY_OF_MONTH,-3);
       days = calendar.get(Calendar.DAY_OF_MONTH);
       System.out.println(days);

       //getTime():日历类---> Date
       Date date = calendar.getTime();
       System.out.println(date);

       //setTime():Date ---> 日历类
       Date date1 = new Date();
       calendar.setTime(date1);
       days = calendar.get(Calendar.DAY_OF_MONTH);
       System.out.println(days);

  }
 @Test
   public void testDate(){
       //偏移量
       Date date1 = new Date(2020 - 1900,9 - 1,8);
       System.out.println(date1);//Tue Sep 08 00:00:00 GMT+08:00 2020
  }

   /*
   LocalDate、LocalTime、LocalDateTime 的使用
   说明:
       1.LocalDateTime相较于LocalDate、LocalTime,使用频率要高
       2.类似于Calendar
    */
   @Test
   public void test1(){
       //now():获取当前的日期、时间、日期+时间
       LocalDate localDate = LocalDate.now();
       LocalTime localTime = LocalTime.now();
       LocalDateTime localDateTime = LocalDateTime.now();

       System.out.println(localDate);
       System.out.println(localTime);
       System.out.println(localDateTime);

       //of():设置指定的年、月、日、时、分、秒。没有偏移量
       LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
       System.out.println(localDateTime1);


       //getXxx():获取相关的属性
       System.out.println(localDateTime.getDayOfMonth());
       System.out.println(localDateTime.getDayOfWeek());
       System.out.println(localDateTime.getMonth());
       System.out.println(localDateTime.getMonthValue());
       System.out.println(localDateTime.getMinute());

       //体现不可变性
       //withXxx():设置相关的属性
       LocalDate localDate1 = localDate.withDayOfMonth(22);
       System.out.println(localDate);
       System.out.println(localDate1);


       LocalDateTime localDateTime2 = localDateTime.withHour(4);
       System.out.println(localDateTime);
       System.out.println(localDateTime2);

       //不可变性
       LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
       System.out.println(localDateTime);
       System.out.println(localDateTime3);

       LocalDateTime localDateTime4 = localDateTime.minusDays(6);
       System.out.println(localDateTime);
       System.out.println(localDateTime4);
  }

   /*
   Instant的使用
   类似于 java.util.Date类

    */
   @Test
   public void test2(){
       //now():获取本初子午线对应的标准时间
       Instant instant = Instant.now();
       System.out.println(instant);//2019-02-18T07:29:41.719Z

       //添加时间的偏移量
       OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
       System.out.println(offsetDateTime);//2019-02-18T15:32:50.611+08:00

       //toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数 ---> Date类的getTime()
       long milli = instant.toEpochMilli();
       System.out.println(milli);

       //ofEpochMilli():通过给定的毫秒数,获取Instant实例 -->Date(long millis)
       Instant instant1 = Instant.ofEpochMilli(1550475314878L);
       System.out.println(instant1);
  }

   /*
   DateTimeFormatter:格式化或解析日期、时间
   类似于SimpleDateFormat

    */

   @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);
       System.out.println(str1);//2019-02-18T15:42:18.797

       //解析:字符串 -->日期
       TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797");
       System.out.println(parse);

//       方式二:
//       本地化相关的格式。如:ofLocalizedDateTime()
//       FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
       DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
       //格式化
       String str2 = formatter1.format(localDateTime);
       System.out.println(str2);//2019年2月18日 下午03时47分16秒


//     本地化相关的格式。如: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);//2019-2-18


//       重点: 方式三:自定义的格式。如: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);//2019-02-18 03:52:09

       //解析
       TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09");
       System.out.println(accessor);

  }

2.Comparator接口的使用

一、说明:Java中的对象,正常情况下,只能进行比较:== 或 != 。不能使用 > 或 < 的 但是在开发场景中,我们需要对多个对象进行排序,言外之意,就需要比较对象的大小。 如何实现?使用两个接口中的任何一个:Comparable 或 Comparator

二、Comparable接口与Comparator的使用的对比: Comparable接口的方式一旦一定,保证Comparable接口实现类的对象在任何位置都可以比较大小。

  • Comparator接口属于临时性的比较。

 /*
   Comparable接口的使用举例: 自然排序
   1.像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式。
   2.像String、包装类重写compareTo()方法以后,进行了从小到大的排列
   3. 重写compareTo(obj)的规则:
       如果当前对象this大于形参对象obj,则返回正整数,
       如果当前对象this小于形参对象obj,则返回负整数,
       如果当前对象this等于形参对象obj,则返回零。
   4. 对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(obj)方法。
      在compareTo(obj)方法中指明如何排序
    */
   @Test
   public void test1(){
       String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
       //
       Arrays.sort(arr);

       System.out.println(Arrays.toString(arr));

  }

   @Test
   public void test2(){
       Goods[] arr = new Goods[5];
       arr[0] = new Goods("lenovoMouse",34);
       arr[1] = new Goods("dellMouse",43);
       arr[2] = new Goods("xiaomiMouse",12);
       arr[3] = new Goods("huaweiMouse",65);
       arr[4] = new Goods("microsoftMouse",43);

       Arrays.sort(arr);

       System.out.println(Arrays.toString(arr));
  }

   /*
   Comparator接口的使用:定制排序
   1.背景:
   当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,
   或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,
   那么可以考虑使用 Comparator 的对象来排序
   2.重写compare(Object o1,Object o2)方法,比较o1和o2的大小:
   如果方法返回正整数,则表示o1大于o2;
   如果返回0,表示相等;
   返回负整数,表示o1小于o2。

    */
   @Test
   public void test3(){
       String[] arr = new String[]{"AA","CC","KK","MM","GG","JJ","DD"};
       Arrays.sort(arr,new Comparator(){

           //按照字符串从大到小的顺序排列
           @Override
           public int compare(Object o1, Object o2) {
               if(o1 instanceof String && o2 instanceof  String){
                   String s1 = (String) o1;
                   String s2 = (String) o2;
                   return -s1.compareTo(s2);
              }
//               return 0;
               throw new RuntimeException("输入的数据类型不一致");
          }
      });
       System.out.println(Arrays.toString(arr));
  }

   @Test
   public void test4(){
       Goods[] arr = new Goods[6];
       arr[0] = new Goods("lenovoMouse",34);
       arr[1] = new Goods("dellMouse",43);
       arr[2] = new Goods("xiaomiMouse",12);
       arr[3] = new Goods("huaweiMouse",65);
       arr[4] = new Goods("huaweiMouse",224);
       arr[5] = new Goods("microsoftMouse",43);

       Arrays.sort(arr, new Comparator() {
           //指明商品比较大小的方式:按照产品名称从低到高排序,再按照价格从高到低排序
           @Override
           public int compare(Object o1, Object o2) {
               if(o1 instanceof Goods && o2 instanceof Goods){
                   Goods g1 = (Goods)o1;
                   Goods g2 = (Goods)o2;
                   if(g1.getName().equals(g2.getName())){
                       return -Double.compare(g1.getPrice(),g2.getPrice());
                  }else{
                       return g1.getName().compareTo(g2.getName());
                  }
              }
               throw new RuntimeException("输入的数据类型不一致");
          }
      });

       System.out.println(Arrays.toString(arr));
  }

2.其他常用类的使用

1.System

2.Math

3.BigInteger 和 BigDecimal

@Test
   public void test1() {
       String javaVersion = System.getProperty("java.version");
       System.out.println("java的version:" + javaVersion);

       String javaHome = System.getProperty("java.home");
       System.out.println("java的home:" + javaHome);

       String osName = System.getProperty("os.name");
       System.out.println("os的name:" + osName);

       String osVersion = System.getProperty("os.version");
       System.out.println("os的version:" + osVersion);

       String userName = System.getProperty("user.name");
       System.out.println("user的name:" + userName);

       String userHome = System.getProperty("user.home");
       System.out.println("user的home:" + userHome);

       String userDir = System.getProperty("user.dir");
       System.out.println("user的dir:" + userDir);

  }

   @Test
   public void test2() {
       BigInteger bi = new BigInteger("1243324112234324324325235245346567657653");
       BigDecimal bd = new BigDecimal("12435.351");
       BigDecimal bd2 = new BigDecimal("11");
       System.out.println(bi);
//         System.out.println(bd.divide(bd2));
       System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP));
       System.out.println(bd.divide(bd2, 25, BigDecimal.ROUND_HALF_UP));

  }

 

posted @   天覆者  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示