JAVA基础课程(第十八天)

JAVA基础课程

第十八天 JAVA常用类

时间类API
JDK8之前的时间API

1.java.lang.System类

		/***
		 * 返回当前时间与1970年1月1日0时0分0秒之间,以毫秒为单位的时间差(时间戳)
		 */
		long time = System.currentTimeMillis();
		System.out.println(time);

2.java.util.Date类

		Date date = new Date();  //使用无参构造器获取本地当前时间(1588757687922)

		System.out.println(date.getTime());//Date获取时间戳

		System.out.println(date.toString());//Date重写toString(Wed May 06 17:34:47 CST 2020)


		Date date1 = new Date(1588757687922L);  //传入时间戳。获取这个时间戳的日期
		System.out.println(date1.toString());

3.java.text.SimpleDateFormat类(时间和字符串时间的转化)

		//时间转字符串
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
		System.out.println(simpleDateFormat.format(date));  //默认格式转换20-5-6 下午5:40

		//yyMMddHHmmss
		SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //转换为固定格式
		System.out.println(simpleDateFormat1.format(date));

		System.out.println("---------------------------");
		//字符串转时间
		try {
			Date date2 = simpleDateFormat1.parse("2020-05-06 17:42:24");
			System.out.println(date2.toString());
		} catch (ParseException e) {
			e.printStackTrace();
		}

4.java.text.Calendar类

		//调用其静态方法
		Calendar calendar = Calendar.getInstance();

		//通过创建其子类GregorianCalendar的对象来创建Calendar
		Calendar calendar1 = new GregorianCalendar();


		//get方法的使用
		System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //当年第几天
		System.out.println(calendar.get(Calendar.DAY_OF_MONTH));  //本月第几天
		System.out.println(calendar.get(Calendar.DAY_OF_WEEK));  //周日是1,周一 是2.。。。周六是7

		System.out.println("**********************");
		//set方法
	    calendar.set(Calendar.DAY_OF_MONTH,22);  //设置第几天
		System.out.println(calendar.get(Calendar.DAY_OF_MONTH));


		//add方法
		calendar.add(Calendar.DAY_OF_MONTH,3);  //增加几天
		System.out.println(calendar.get(Calendar.DAY_OF_MONTH));


		//转Date
		System.out.println(calendar.getTime());  //Mon May 25 18:41:22 CST 2020

		//date转calendar
		calendar.setTime(new Date());

		System.out.println(calendar.getTime());  //Mon May 25 18:41:22 CST 2020

JDK8之后的时间API

​ java.time包下的时间

(1)LocalDateTime,LocalDate,LocalTime

	//获取当前时间now()
		LocalDateTime localDateTime =  LocalDateTime.now();
		LocalDate localDate = LocalDate.now();
		LocalTime localTime = LocalTime.now();
		System.out.println(localDateTime);  //2020-05-06T18:48:19.743
		System.out.println(localDate);   //2020-05-06
		System.out.println(localTime);  //18:48:19.744


		//设置时间of(),没有偏移量
		LocalDateTime localDateTime1 = LocalDateTime.of(2020,10,4,12,30);
		System.out.println(localDateTime1); //2020-10-04T12:30


		System.out.println("******************");
		System.out.println(localDateTime.getDayOfYear());  //年
		System.out.println(localDateTime.getDayOfMonth());  //本月第几天
		System.out.println(localDateTime.getDayOfWeek());  //星期(WEDNESDAY)

		System.out.println("******************");
		System.out.println(localDateTime.getMonth());  //几月(MAY)
		System.out.println(localDateTime.getMonthValue());  //几月(5)
		System.out.println(localDateTime.getMinute());  // minute-of-hour几分


		System.out.println(localDateTime.withDayOfMonth(22));  //设置为几日
		System.out.println(localDateTime);

(2)Instant

		//时间线上的某个瞬时
		//now 获取本初子午线对应的标准时间
		Instant instant = Instant.now();
		System.out.println(instant);


		//添加时间的偏移量
		OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
		System.out.println(offsetDateTime);

(3) DateTimeFormatter进行日期格式转换

System.out.println("*****************方式1");
		DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
		LocalDateTime localDateTime2 = LocalDateTime.now();
		String str = formatter.format(localDateTime2);
		System.out.println(str);  //2020-05-06T19:10:58.042

		TemporalAccessor temporal = formatter.parse(str);
		System.out.println(temporal); //{},ISO resolved to 2020-05-06T19:12:09.765


		System.out.println("*****************方式2");
		//方式2
		DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
		String str2 = formatter1.format(localDateTime2);
		System.out.println(str2);  //2020年5月6日 下午07时16分35秒

		TemporalAccessor temporal2 = formatter1.parse(str2);
		System.out.println(temporal2); //{},ISO resolved to 2020-05-06T19:12:09.765

		System.out.println("******************方式3");
		//方式3自定义格式
		DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String str3 = formatter2.format(localDateTime2);
		System.out.println(str3);  //2020-05-06 19:18:51
		//字符串转日期
		TemporalAccessor parse3 = formatter2.parse(str3);
		System.out.println(parse3);

Java比较器
自然排序:java.lang.Comparable
 * 1.String等都实现了Comparable接口,重写了compareTo(obj)方法
 * 2.重写compareTo(obj)规则
 *   如果当前对象this大于形参对象obj对象,则返回正整数
 *   如果当前对象this小于形参对象obj对象,则返回负整数
 *   如果当前对象this等于形参对象obj对象,则返回0
package com.test.course.compartest;


import java.util.Arrays;

/**
 * 〈Comparable〉
 *
 * @author PitterWang
 * @create 2020/5/6
 * @since 1.0.0
 */
public class ComparableTest {

	public static void main(String[] args) {
		String[] arr = new String[]{"BB","AA","EE","CC","DD"};

		Arrays.sort(arr);

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


		Goods goods = new Goods(1,"东东");
		Goods goods1 = new Goods(2,"涛涛");

		Goods[] goods2 = new Goods[]{goods,goods1};
		Arrays.sort(goods2);
		for(Goods f : goods2){
			System.out.println(f);
		}
	}

}

class Goods implements Comparable{

	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Goods(int id, String name) {
		this.id = id;
		this.name = name;
	}

	@Override
	public int compareTo(Object o) {
		if(o instanceof Goods){
			Goods goods = (Goods)o;

			if(this.id > goods.id){
				return 1;
			}else if(this.id < goods.id){
				return -1;
			}else{
				return 0;
			}
		}

		throw new RuntimeException("异常");
	}

	@Override
	public String toString() {
		return "Goods{" +
				"id=" + id +
				", name='" + name + '\'' +
				'}';
	}
}
定制排序:java.uril.Comparator
//自动排序
		String[] arr = new String[]{"BB","AA","EE","CC","DD"};

		Arrays.sort(arr);

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

		//字符串自定义排序(逆序排序)
		String[] arr2 = new String[]{"BB","AA","EE","CC","DD"};

		Arrays.sort(arr2, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return -o1.compareTo(o2);
			}
		});
		System.out.println(Arrays.toString(arr2));


		String[] arr3 = new String[]{"BB","AA","EE","CC","DD"};

		//JAVA8的lambda?
		Arrays.sort(arr3, (o1,o2) -> -o1.compareTo(o2));
		System.out.println(Arrays.toString(arr3));


		/***
		 * 自定义排序自己实现的类
		 */
		Goods goods1 = new Goods(2,"东东");
		Goods goods = new Goods(1,"涛涛");

		Goods[] goods2 = new Goods[]{goods,goods1};
		Arrays.sort(goods2,(o1, o2)-> o1.getName().compareTo(o2.getName())
		);
		for (Goods goods3 : goods2) {
			System.out.println(goods3.toString());
		}

System类

System类代表系统类,构造器是private,所以无法实例化,但是内部成员都是static,所以方便使用

System里的成员变量:in,out,err

System里的成员方法:

   
    //获取系统时间
    public static native long currentTimeMillis();

	//退出程序
    public static void exit(int status) {
        Runtime.getRuntime().exit(status);
    }
    
    //请求系统进行垃圾回收
    public static void gc() {
        Runtime.getRuntime().gc();
    }
    
    //根据key获取系统属性名
   public static String getProperty(String key) {
        checkKey(key);
        SecurityManager sm = getSecurityManager();
        if (sm != null) {
            sm.checkPropertyAccess(key);
        }

        return props.getProperty(key);
    }
Math类

java提供了一系列用于科学计算的Math类。

  /***
  *获取绝对值
  */
  public static double abs(double a) {
        return (a <= 0.0D) ? 0.0D - a : a;
    }
    
  三角函数,底层用StrictMath类实现
 * {@code acos}), use the "IEEE 754 core function" version
 * (residing in a file whose name begins with the letter
 * {@code e}).  The methods which require {@code fdlibm}
 * semantics are {@code sin}, {@code cos}, {@code tan},
 * {@code asin}, {@code acos}, {@code atan},
 * {@code exp}, {@code log}, {@code log10},
 * {@code cbrt}, {@code atan2}, {@code pow},
 * {@code sinh}, {@code cosh}, {@code tanh},
 * {@code hypot}, {@code expm1}, and {@code log1p}.
 
 //平方根
     public static double sqrt(double a) {
        return StrictMath.sqrt(a); // default impl. delegates to StrictMath
                                   // Note that hardware sqrt instructions
                                   // frequently can be directly used by JITs
                                   // and should be much faster than doing
                                   // Math.sqrt in software.
    }


//a的b此幂
  public static double pow(double a, double b) {
        return StrictMath.pow(a, b); // default impl. delegates to StrictMath
    }


方法很多!~~~~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值