Loading

正则表达式-random类-日期时间处理


返回 我的技术栈(Technology Stack)



正则表达式的概述和简单使用


  • 正则表达式
    • 是指一个用来描述或者匹配一系列符合某个语法规则的字符串的单个字符串。其实就是一种规则。有自己特殊的应用。

    • 作用:比如注册邮箱,邮箱有用户名和密码,一般会对其限制长度,这个限制长度的事情就是正则表达式做的

        校验QQ是否符合要求
        	1、要求必须是5-15位数字		2、0不能开头
        	3、必须都是数字
        
        先用非正则表达式做
        public static void main(String[] args) {
        	System.out.println(checkQQ("012345"));
        	System.out.println(checkQQ("123654"));
        }
      
        public static boolean checkQQ(String qq) {
        	boolean flag = true;     //如果校验QQ不符合要求就把flag置为false,符合要求就直接返回
      
        	if (qq.length() >= 5 && qq.length() <= 15) {
        		if(!qq.startsWith("0")) {  //获取字符串的第一个数字,并判断
        			char[] arr = qq.toCharArray();  //将字符串转换成字符数组
        			for(int i = 0; i < arr.length; i ++) {
        				char ch = arr[i];   //记录每一个字符
        				if(!(ch >= '0' && ch <= '9')) {
        					flag = false;
        					break;	
        				}
        			}
        		}else {
        			flag = false;   //以0开头,不符合QQ标准
        		}
        	}else {
        		flag = false; //长度不符合
        	}
        	return flag;
        } 
      
        输出结果:false
        		 true
      
        用正则表达式做
        public static void main(String[] args) {
        	String regex = "[1-9]\\d{4,14}";    //   \\d代表任意数字字符
      
        	System.out.println("264563".matches(regex));
        	System.out.println("0064563".matches(regex));
        	System.out.println("264c63".matches(regex));
        }
      
        输出结果:true
        		 false
        		 false
      

字符类演示


  • 字符类

    • [abc] a、b 或 c(简单类)

        String regex = "[abc]";    //[]代表单个字符
        System.out.println("a".matches(regex));
        System.out.println("b".matches(regex));
        System.out.println("c".matches(regex));
        System.out.println("d".matches(regex));
        System.out.println("1".matches(regex));
        System.out.println("$".matches(regex));
           输出结果:true
        			true
        			true
        			false
        			false
        			false
      
    • [^abc] 任何字符,除了 a、b 或 c(否定)

        String regex = "[^abc]";    //[]代表单个字符
        System.out.println("a".matches(regex));
        System.out.println("b".matches(regex));
        System.out.println("c".matches(regex));
        System.out.println("d".matches(regex));
        System.out.println("1".matches(regex));
        System.out.println("$".matches(regex));
        System.out.println("10".matches(regex));   //10是两个字符,不是单个字符
           输出结果:false
        			false
        			false
        			true
        			true
        			true
        			false
      
    • [a-zA-Z] a到 z 或 A到 Z,两头的字母包括在内(范围)

        String regex = "[a-zA-Z]";    //[]代表单个字符
        System.out.println("a".matches(regex));
        System.out.println("A".matches(regex));
        System.out.println("z".matches(regex));
        System.out.println("b".matches(regex));
        System.out.println("Z".matches(regex));
        System.out.println("1".matches(regex));
        System.out.println("$".matches(regex));
           输出结果:true
        			true
        			true
        			true
        			true
        			false
        			false
      
    • [a-d[m-p]] a到d 或 m到p:[a-dm-p] (并集)

        String regex = "[a-d[m-p]]";
        System.out.println("a".matches(regex));
        System.out.println("c".matches(regex));
        System.out.println("d".matches(regex));
        System.out.println("e".matches(regex));
        System.out.println("f".matches(regex));
      
        System.out.println("A".matches(regex));
        System.out.println("2".matches(regex));
        System.out.println("l".matches(regex));
        System.out.println("z".matches(regex));
        System.out.println("m".matches(regex));
      
        System.out.println("o".matches(regex));
        	   输出结果:true
        				true
        				true
        				false
        				false
      
        				false
        				false
        				false
        				false
        				true
      
        				true
      
    • [a-z&&[def]] d、e 或 f(交集) 交集就是d、e、f 。也就是判断是否包含d、e、f

        String regex = "[a-z&&[def]]";
        System.out.println("a".matches(regex));
        System.out.println("d".matches(regex));
        	输出结果:false
        			 true
      
    • [a-z&&[^bc]] a到z,除了b和c:[ad - z] (减去)

        String regex = "[a-z&&[^bc]]";
        System.out.println("a".matches(regex));
        System.out.println("b".matches(regex));
        System.out.println("1".matches(regex));
        	输出结果:true
        			 false
        			 false
      
    • [a-z&&[^m-p]] a到z,而非m到p:[a-lq-z] (减去)

        String regex = "[a-z&&[^m-p]]";
        System.out.println("m".matches(regex));
        System.out.println("a".matches(regex));
        System.out.println("z".matches(regex));
        System.out.println("n".matches(regex));
       		   输出结果:false
        				true
        				true
        				false
      
  • [0-9] 0到9的字符都包括

      	String regex = "[0-9]";
      	System.out.println("0".matches(regex));
      	System.out.println("5".matches(regex));
      	System.out.println("z".matches(regex));
      	System.out.println("10".matches(regex));
      	   输出结果:true
      				true
      				false
      				false
    

预定字符类演示


  • . 任何字符

      		String regex = ".";
      		System.out.println("a".matches(regex));
      		System.out.println("ab".matches(regex));
      		System.out.println("-----------------------");
      		String reg = "..";
      		System.out.println("a".matches(reg));
      		System.out.println("ab".matches(reg));
    
      		输出结果:true
      				false
      				-----------------------
      				false
      				true
    
  • \d 数字:[0-9]

      	String regex = "\\d";     //   \代表转义字符,如果想表示\d的话,需要\\d
      	System.out.println("0".matches(regex)); 
      	System.out.println("a".matches(regex)); 
      	System.out.println("9".matches(regex)); 
    
      	输出结果:true
      			 false
      			 true
    
  • \D 非数字:[^0-9]

      	String regex = "\\D";
      	System.out.println("0".matches(regex)); 
      	System.out.println("9".matches(regex)); 
      	System.out.println("a".matches(regex)); 
    
      	输出结果:false
      			 false
      			 true
    
  • \s 空白字符:[ \t\n\xoB\f\r]

      	String regex = "\\s";
      	System.out.println(" ".matches(regex)); 
      	System.out.println("		".matches(regex)); //一个tab键
      	System.out.println("    ".matches(regex)); //四个空格
    
      	输出结果:true
      			 true
      			 false
    
  • \s 非空白字符: [^\s]

      	String regex = "\\S";
      	System.out.println(" ".matches(regex)); 
      	System.out.println("		".matches(regex)); //一个tab键
      	System.out.println("a".matches(regex)); 
    
      	输出结果:false 
      			 false 
      			 true			
    
  • \w 单词字符:[a-zA-z_0-9]

      	String regex = "\\w";
      	System.out.println("a".matches(regex)); 
      	System.out.println("	z".matches(regex)); //一个tab键
      	System.out.println("_".matches(regex)); 
      	System.out.println("%".matches(regex));
    
      	输出结果:true
      			 true
      			 true
      			 false
    
  • \W 非单词字符:[^\w]

      	String regex = "\\W";
      	System.out.println("a".matches(regex)); 
      	System.out.println("	z".matches(regex)); //一个tab键
      	System.out.println("_".matches(regex)); 
      	System.out.println("%".matches(regex));
    
      	输出结果:false
      			 false
      			 false
      			 true
    

数量词(Greedy)


  • x? x,一次或一次也没有

      		String regex = "[abc]?";
      		System.out.println("a".matches(regex));
      		System.out.println("b".matches(regex));
      		System.out.println("c".matches(regex));
      		System.out.println("d".matches(regex));   //是针对已知的一次也没有
      		System.out.println("".matches(regex));
    
      		   输出结果:true
      					true
      					true
      					false
      					true
    
  • x* x,零次或多次

      		String regex = "[abc]*";
      		System.out.println("abc".matches(regex));
      		System.out.println("a".matches(regex));
      		System.out.println("c".matches(regex));
      		System.out.println("d".matches(regex));
      		System.out.println("".matches(regex));
    
    
      	输出结果:true
      			true
      			true
      			false
      			true
    
  • x+ x,一次或多次

      		String regex = "[abc]+";
      		System.out.println("abc".matches(regex));
      		System.out.println("aaabbbccc".matches(regex));
      		System.out.println("c".matches(regex));
      		System.out.println("dddddvvvvcccc".matches(regex));
      		System.out.println("".matches(regex));
    
      		输出结果:true
      				true
      				true
      				false
      				false
    
  • x{n} x,恰好n次

      		String regex = "[abc]{5}";
      		System.out.println("abcba".matches(regex));
      		System.out.println("aaabaabcabcbcbac".matches(regex));
      		System.out.println("abcb".matches(regex));
      		System.out.println("dddddvvvvcccc".matches(regex));
      		System.out.println("abcbaaba".matches(regex));
      		
      		输出结果:true
      				false
      				false
      				false
      				false
    
  • x{n,} x,至少n次

      		String regex = "[abc]{5,}";
      		System.out.println("abcba".matches(regex));
      		System.out.println("aaabaabcabcbcbac".matches(regex));
      		System.out.println("abcb".matches(regex));
      		System.out.println("dddddvvvvcccc".matches(regex));
      		System.out.println("abcbaaba".matches(regex));
      		
      		输出结果:true
      				true
      				false
      				false
      				true
    
  • x{n,m} x,至少n次,但是不超过m次

      		String regex = "[abc]{5,15}";
      		System.out.println("abcba".matches(regex));
      		System.out.println("aaabaabcabcbcbac".matches(regex));
      		System.out.println("abcb".matches(regex));
      		System.out.println("dddddvvvvcccc".matches(regex));
      		System.out.println("abcbaaba".matches(regex));
    
      		输出结果:true
      				false
      				false
      				false
      				true
    

正则表达式的分割功能


		String s = "金三胖 郭美美 李林";
		String[] arr = s.split(" ");

		for(int i = 0 ; i < arr.length; i ++) {
			System.out.println(arr[i]);
		} 

		   输出结果:金三胖
					郭美美
					李林

		String s = "金三胖.郭美美.李林";
	//String[] arr = s.split(".");  无结果输出,因为 . 是通配字符,与所有字符都可匹配
		String[] arr = s.split("\\.");  //通过转义就可以

		for(int i = 0 ; i < arr.length; i ++) {
			System.out.println(arr[i]);
		} 

		   输出结果:金三胖
					郭美美
					李林

把给定字符串中的数字排序


  • 需求:有一个字符串:“91 27 46 38 50”

  • 用代码实现输出:“27 38 46 50 91”

      public static void main(String[] args) {
      	String s = "91 27 46 38 50";
      	
      	String[] sArr = s.split(" ");  // 将字符串切割成字符串数组
    
      	int[] arr = new int[sArr.length];
      	for(int i = 0; i < arr.length; i ++) {
      		arr[i] = Integer.parseInt(sArr[i]);  //将数字字符串转换成数字
      	}
    
      	Arrays.sort(arr); //排序
    
      	//将排序后的结果遍历,并拼接成一个字符串
      	StringBuilder sb = new StringBuilder();
      	for(int i = 0; i < arr.length; i ++) {
      		if(i == arr.length) {
      			sb.append(arr[i]);
      		}else {
      			sb.append(arr[i] + " ");
      		}
      	}
    
      	System.out.println(sb);  //默认调用toString()方法
    
      }
    
      输出结果:27 38 46 50 91
    

正则表达式的替换功能


  • 正则表达式的替换功能
    • String类的功能:public String replaceAll(String regex,String replacement)

        public static void main(String[] args) {
        	String s = "wo111ai222heima";
        	String regex = "\\d";  //  \\d代表的是任意数字
      
        	String s2 = s.replaceAll(regex,"");
        	System.out.println(s2);
      
        }
      
        输出结果:woaiheima
      

正则表达式的分组功能


  • 正则表达式的分组功能

    • 捕获组可以通过从左到右计算其开括号来编号。例如,在表达式 ((A)(B(C))) 中,存在四个这样的组:
  •   1     ((A)(B(C))) 
      2     (A 
      3     (B(C)) 
      4     (C) 
    
      组零始终代表整个表达式。
    
      public static void main(String[] args) {
      	//叠词:快快乐乐   高高兴兴
      	String regex = "(.)\\1(.)\\2";   //  \\1代表第一组又出现一次    \\2代表第二组又出现一次
      	System.out.println("快快乐乐".matches(regex));
      	System.out.println("快乐乐乐".matches(regex));
      	System.out.println("高高兴兴".matches(regex));
      	System.out.println("死啦死啦".matches(regex));
      }
    
         输出结果:true
      			false
      			true
      			false
    
      public static void main(String[] args) {
      	//叠词:死啦死啦   高兴高兴
      	String regex = "(..)\\1";   //  \\1代表第一组又出现一次    \\2代表第二组又出现一次
      	System.out.println("快快乐乐".matches(regex));
      	System.out.println("高兴高兴".matches(regex));
      	System.out.println("nihaonihao".matches(regex));
      	System.out.println("nihaniha".matches(regex));
      	System.out.println("死啦死啦".matches(regex));
      }
    
         输出结果:false
      			true
      			false
      			false
      			true
    
  • 练习

        	1、需求:请按照叠词切割: "sdqqfgkkkhjppppkl";
    
      		String s = "sdqqfgkkkhjppppkl";
    
      		String regex = "(.)\\1+";   //  +代表第一组出现一次到多次
      		String [] arr = s.split(regex);
      		
      		for(int i = 0; i < arr.length; i ++) {
      			System.out.println(arr[i]);
      		}
    
      	   输出结果:sd
      				fg
      				hj
      				kl
    
      2、需求:我我....我...我.要...要要...要学....学学..学.编..编编.编.程.程.程..程
         将字符串还原成:“我要学编程”。
    
      	String s = "我我....我...我.要...要要...要学....学学..学.编..编编.编.程.程.程..程";
      	String s2 = s.replaceAll("\\.+","");
      	String s3 = s2.replaceAll("(.)\\1+","$1");  //$1代表第一组中的内容
      	
      	System.out.println(s3);
    
      	输出结果:我要学编程
    

Pattern和Matcher的概述


  • 典型的调用顺序是

  • Pattern p = Pattern.compile("a*b");

  • Matcher m = p.matcher("aaaaab");

  • boolean b = m.matches();

      import java.util.regex.Matcher;
      import java.util.regex.Pattern;
      public static void main(String[] args) {
      	 Pattern p = Pattern.compile("a*b");  // 获取到正则表达式
      	 Matcher m = p.matcher("aaaaab");  //获取匹配器
      	 boolean b = m.matches();   // 看是否能够匹配,匹配成功就返回true
    
      	 System.out.println(b);
      	
      	 System.out.println("aaaaab".matches("a*b"));   //与上面的结果一样
    
      }
    
      输出结果:true
      		 true
    
  • 应用

    • 需求:把一个字符串中的手机号码获取出来

      	import java.util.regex.Matcher;
      	import java.util.regex.Pattern;
      	public static void main(String[] args) {
      		String s = "我的手机号码18988888888,曾经用过18987654321,还用过18812345678";
      		String regex = "1[3578]\\d{9}";  // 手机号的正则表达式
      		
      		Pattern p = Pattern.compile(regex);
      		Matcher m = p.matcher(s);
      
      		while(m.find()){  //必须县调用先找的方法,再获取
      			System.out.println(m.group());
      		} 
      
      	}
      
      	   输出结果:18988888888
      				18987654321
      				18812345678
      

Math类概述和方法使用


  • Math类概述
    • Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
  • 成员方法
    • public static int abs(int a)

        System.out.println(Math.abs(-10));   //取绝对值
        输出结果:10
      
    • public static double ceil(double a)

        System.out.println(Math.ceil(12.3));  // ceil天花板  向上取整,但返回的是double值
        System.out.println(Math.ceil(12.99));
        输出结果:13.0
        		 13.0
      
    • public static double floor(double a)

        System.out.println(Math.floor(12.3));  // floor地板  向下取整,但返回的是double值
        System.out.println(Math.floor(12.99));
        输出结果:12.0
        		 12.0
      
    • public static int max(int a,int b) min自学

        System.out.println(Math.max(20,30));   //获取两个值中的最大值,若两个相同,则输出其中一个
        输出结果:30
      
        System.out.println(Math.min(20,30));   //获取两个值中的最小值,若两个相同,则输出其中一个
        输出结果:20
      
    • public static double pow(double a,double b)

        System.out.println(Math.pow(2,3));  //2.0^3.0
        输出结果:8.0
      
    • public static double random()

        //生成0.0到1.0之间的所有小数,包括0.0,不包括1.0
        System.out.println(Math.random());
        输出结果:0.5454808034297881
      
    • public static int round(float a) 参数为double的自学

        //四舍五入
        System.out.println(Math.round(12.3f));
        System.out.println(Math.round(12.9f));
        输出结果:12
        		 13
      
        System.out.println(Math.round(12.3d));
        System.out.println(Math.round(12d));
        System.out.println(Math.round(12.9d));
        输出结果:12
        		 12
        		 13
      
    • public static double sqrt(double a)

        System.out.println(Math.sqrt(4));
        System.out.println(Math.sqrt(2));
        System.out.println(Math.sqrt(3));
      
         输出结果:2.0
        		  1.4142135623730951
        		  1.7320508075688772
      

Random类的概述和方法使用


  • A:Random类的概述
    • 此类用于产生随机数如果用相同的种子创建两个 Random 实例,
    • 则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。
  • B:构造方法
    • public Random()
    • public Random(long seed)
  • C:成员方法
    • public int nextInt()

    • public int nextInt(int n)(重点掌握)

        import java.util.Random;
        public static void main(String[] args) {
        	Random r = new Random();
        	for(int i = 0; i < 10; i++) {
        		System.out.println(r.nextInt());
        	}
        }
      
        输出结果:624260102
        		1824990795
        		404062941
        		316896722
        		-1018346437
        		-66081322
        		1895796053
        		-393036661
        		-542094666
        		714078869
      
        /*************************************/
      
        import java.util.Random;
        public static void main(String[] args) {
        	Random r2 = new Random(1001);   //指定种子,算出的随机数是一样的(多次运行结果一样)
      
        	int a = r2.nextInt();
        	int b = r2.nextInt();
      
        	System.out.println(a);
        	System.out.println(b);
        	}
        }
        		
        输出结果:-1245131070
        		 -2078988849
      
        /**************************************/
      
        Random r = new Random();
        System.out.println(r.nextInt(100));  //随机输出0-99(包括0和99)
      

System类的概述和方法使用


  • System类的概述

    • System 类包含一些有用的类字段和方法。它不能被实例化(私有化了)。
  • 成员方法

    • public static void gc()

        System.gc();   //运行垃圾回收机制,相当于呼喊保洁阿姨
      
    • public static void exit(int status)

        //终止当前正在运行的Java虚拟机
        System.exit(0);  //括号里一般填写1    运行该条指令后,以后的代码不运行,即已经退出JVM
        System.out.println("11111111111");
      
    • public static long currentTimeMillis()

        //返回以毫秒为单位的当前时间
        long start = System.currentTimeMillis();    //1秒等于1000毫秒
        for(int i = 0; i < 1000; i ++) {
        	System.out.println("*");
        }
        long end = System.currentTimeMillis();
      
        System.out.println(end - start);
      
    • pubiic static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

        		public static void main(String[] args) {
      
        				int [] src = {11,22,33,44,55};
        				int [] dest = new int[8];
        				for(int i = 0;i < dest.length; i++) {
        						System.out.print(dest[i] + "  ");
        				}
      
        				System.out.println();
        				System.arraycopy(src, 0, dest, 0, src.length);  
        				// System.arraycopy(Object src,     int srcPos,          Object dest             int destPos,           int length) 
        				//                   源数组          源数组中的起始位置        目标数组           目标数组中的起始位置    要复制的数组元素的数量
      
        				for (int i = 0; i < dest.length ; i ++ ) {
        					System.out.print(dest[i] + "  ");
        				}
      
        		}
      
        		输出结果:0  0  0  0  0  0  0  0
        				11  22  33  44  55  0  0  0
      
  • 案例演示

    • System类的成员方法使用

BigInteger类的概述和方法使用


  • A:BigInteger的概述
    • 可以让超过Integer范围内的数据进行运算(即可以放很大的整数)
  • B:构造方法
    • public BigInteger(String val)
  • C:成员方法
    • public BigInteger add(BigInteger val)

    • public BigInteger subtract(BigInteger val)

    • public BigInteger multiply(BigInteger val)

    • public BigInteger divide(BigInteger val)

    • public BigInteger[] divideAndRemainder(BigInteger val)

        	BigInteger bi1 = new BigInteger("100");
        	BigInteger bi2 = new BigInteger("2");
      
        	System.out.println(bil.add(bi2));   // +
        	System.out.println(bil.subtract(bi2));  // -
        	System.out.println(bil.multiply(bi2));  // *
        	System.out.println(bil.divide(bi2));  // 除(/)
      
        	BigInteger[] arr = bil.divideAndRemainder(bi2);  //取除数和余数
      
        	for (int i = 0; i < arr.length; i ++) {
        		System.out.println(arr[i]);
        	}
      
        	输出结果:102
        			 98
        			 200
        			 50
        			 50
        			 0
      

BigDecimal类的概述和方法使用


  • A:BigDecimal的概述
    • 由于在运算的时候,float类型和double很容易丢失精度。

        System.out.println(2.0 - 1.1);
        输出结果:0.8999999999999999
      
    • 所以,为了能精确的表示、计算浮点数,Java提供了BigDecimal

    • 不可变的、任意精度的有符号十进制数。

  • B:构造方法
    • public BigDecimal(String val)
  • C:成员方法
    • public BigDecimal add(BigDecimal augend)
    • public BigDecimal subtract(BigDecimal subtrahend)
    • public BigDecimal multiply(BigDecimal multiplicand)
    • public BigDecimal divide(BigDecimal divisor)
  • D:案例演示
    • BigDecimal类的构造方法和成员方法使用

        public static void main(String [] args) {
        		BigDecimal bd1 = new BigDecimal(2.0);     //这种方式在开发中不推荐,因为不够精确
        		BigDecimal bd2 = new BigDecimal(1.1);
        
        		System.out.println(bd1.subtract(bd2));
        
        		BigDecimal bd3 = new BigDecimal("2.0");   //通过构造中传入字符串的方式,开发推荐
        		BigDecimal bd4 = new BigDecimal("1.1");
        
        		System.out.println(bd3.subtract(bd4));
      
        		BigDecimal bd5 = new BigDecimal("2.0");   //这种在开发中也推荐
        		BigDecimal bd6 = new BigDecimal("1.1");
      
        		System.out.println(bd5.subtract(bd6));
        		
        }
      
        输出结果:0.89999999999999991118218029987375
        0.9
        0.9
      

Date类的概述和方法使用(是util包下的,不能导入sql包的)


  • A:Date类的概述

    • 类 Date 表示特定的瞬间,精确到毫秒。
  • B:构造方法

    • public Date()

    • public Date(long date)

             public static void main(String [] args) {
      
        	Date d1 = new Date();   //如果没有传参数代表的是当前时间
        	System.out.println(d1);
      
        	Date d2 = new Date(0);  //如果构造方法中参数传0,代表的是1970年1月1日
        							//但是打印的是8点事因为我们处于东八区
        	System.out.println(d2);
        	}
      
        	输出结果:Tue Feb 27 22:39:49 CST 2018
        			 Thu Jan 01 08:00:00 CST 1970
      
  • C:成员方法

    • public long getTime()

        Date d1 = new Date();
        System.out.println(d1.getTime());  //通过时间对象获取毫秒值
        System.out.println(System.currentTimeMillis());   //通过系统类的方法获取当前时间毫秒值
      
    • public void setTime(long time)

        Date d1 = new Date();
        d1.setTime(1000);    //1秒 = 1000毫秒    设置毫秒值,改变时间对象
        System.out.println(d1);
        输出结果:Thu Jan 01 08:00:01 CST 1970
      

SimpleDateFormat类实现日期和字符串的相互转换


  • A:DateFormat类的概述(抽象类,不可实例化)
    • DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。是抽象类,所以使用其子类SimpleDateFormat
  • B:SimpleDateFormat构造方法
    • public SimpleDateFormat()
    • public SimpleDateFormat(String pattern)
  • C:成员方法
    • public final String format(Date date)

    • public Date parse(String source)

        Date d = new Date();   //获取当前时间对象
        SimpleDateFormat sdf = new SimpleDateFormat();  //创建日期格式化类对象
        System.out.println(sdf.format(d));  //18-6-6 下午 9:31
      
        /***********************/
      
        Date d = new Date();   //获取当前时间对象
        SimpleDateFormat sdf = new SimpleDateFormat(yyyy/MM/dd HH:mm:ss);  //输出结果:2088/06/06 21:34:48
        SimpleDateFormat sdf = new SimpleDateFormat(yyyy年MM月dd 日 HH:mm:ss);  //输出结果:2088年06月06 日 21:34:48
        System.out.println(sdf.format(d));  //日期对象转换成字符串
      
        /******************************/
      
        //将时间字符串转换成日期对象
        String str = "2000年08月08日 08:08:08";
        SimpleDateFormat sdf = new SimpleDateFormat(yyyy年MM月dd日 HH:mm:ss); //与字符串格式对应
        Date d = sdf.parse(str);
        System.out.println(d);
        输出结果:Tue Aug 08:08:08 CST 2000
      

你来到这个世界多少天案例(掌握)


  • A:案例演示
    • 需求:算一下你来到这个世界多少天?

        public static void main(String [] args) {
        	//1、将生日字符串和今天字符串存在String类型中
        	String birthday = "1983年07月08日";
        	String today = "2088年6月6日";
      
        	//2、定义日期格式化对象
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
      
        	//3、将日期字符串转换成日期对象
        	Date d1 =sdf.parse(birthday);
        	Date d2 =sdf.parse(today);
      
        	//4、通过日期对象算出时间毫秒值
        	long time = d2.getTime() - d1.getTime();
      
        	//5、将两个时间毫秒值相减的值,转换成年
        	System.out.println(time/1000/60/60/24/365);
        } 
      
        	输出结果:104
      

Calendar类的概述和获取日期的方法


  • A:Calendar类的概述
    • Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
  • B:成员方法
    • public static Calendar getInstance()

    • public int get (int field)

        	public static void main(String [] args) {
        		Calendar c = calendar.getInstance();   //父类引用子类对象
        		
        		System.out.println(c.get(Calendar.YEAR));  //通过字段获取年
        		System.out.println(c.get(Calendar.MONTH));  //通过字段获取月,但这里月是从0开始编号的
        		System.out.println(c.get(Calendar.DAY_OF_MONYH));  //月中的第几天
        		System.out.println(c.get(Calendar.DAY_OF_WEEK));  //周日是第一天,周六是最后一天
      
        		System.out.println(c.get(Calendar.YEAR) + "年" + getNum((c.get(Calendar.MONTH) + 1)) + "月" +
        		getNum( c.get(Calendar.DAY_OF_MONYH)) + "日" + getWeek(c.get(Calendar.DAY_OF_WEEK)) );
        	} 
      
        	public static String getWeek(int week) {
        		String [] arr = {"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        		return arr[week];
        	}
      
        	public static String getNum(int num) {
        		return num > 9 ? "" + num : "0" + num ;
        	}
      
        	输出结果:2088
        			 5
        			 6
        			 1
        			 2088年06月06日星期日
      

Calendar类的add()和set()方法


	Calendar c = Calendar.getInstance();
	c.add(Calendar.MONTH,-1);   //对指定的字段进行向前加或是向后减
	c.set(Calendar.YEAR,2000);   //修改指定字段  输出结果被替换成2000
	c.set(2000,7,8);   //可以同时修改年月日

判断闰年和平年


	import java.util.Calendar;
	import java.util.Scanner;
	class Hello {
	     public static void main(String [] args) {
			 Scanner sc = new Scanner(System.in);
			 System.out.println("请输入年份,判断该年是闰年还是平年:");
			//int year = sc.nextInt(); 仿写
			 String line = sc.nextLine();   //录入数字字符串
			 int year = Integer.parseInt(line);    //将数字字符串转换成数字
			 boolean b = getYear(year);
			 System.out.println(b);
			
		}
	
		private static boolean getYear(int year) {
			Calendar c = Calendar.getInstance();
			c.set(year, 2 , 1);
			//将日向前减去1
			c.add(Calendar.DAY_OF_MONTH, -1);
	        //判断是否29天
			return c.get(Calendar.DAY_OF_MONTH)  == 29;
		}
		 
	}

	   输出结果:请输入年份,判断该年是闰年还是平年:
				2088
				true

posted @ 2021-03-28 00:19  言非  阅读(179)  评论(0)    收藏  举报