一.辅助类
1.System
System.out.println();
2.Scanner
Scanner sc = new Scanner(System.in);
3.Random
随机数
4.Math
数学运算
5.日期
(1)Date
import java.util.Date;
获取当前时间
package com.ffyc;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) throws InterruptedException {
//Date d = new Date();
//System.out.println("当前时间:"+d);
//System.out.println("当前时间毫秒数:"+d.getTime());
while (true){
Date dx = new Date();
System.out.println(dx);
System.out.println(dx.getTime());
//延迟1秒
Thread.sleep(1000);
}
}
}
(2)System.currentTimeMillis()
获取当前系统的毫秒数
package com.ffyc;
public class DateDemo02 {
public static void main(String[] args) {
//String str = "a";
StringBuilder sb = new StringBuilder("a");
long s1 = System.currentTimeMillis();
for(int i = 0;i < 100000;i++){
//str += "b";
//System.out.println(str);
sb.append("b");
}
long s2 = System.currentTimeMillis();
System.out.println("耗时:" +(s2 - s1)+ "ms");
}
}
(3)SimpleDateFormat(日期的格式转换类)
格式化表示
Date对象格式化输出
String---->Date
sdf.parse("2024/05/01")---->Date
Integer.parseInt("123")---->123
Date---->String
sdf.format(日期类)
格式:y M d H m s
package com.ffyc;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Date03 {
public static void main(String[] args) throws InterruptedException {
while (true){
Date d = new Date();
//格式化输出
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/ HH:mm:ss");
String today = simpleDateFormat.format(d);
System.out.println(today);
Thread.sleep(1000);
}
}
}
(4)Calendar日历
YEAR + MONTH + DAY_OF_MONTH
YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
YEAR + DAY_OF_YEAR
YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
package com.ffyc;
import java.util.Calendar;
public class TestCalendar {
public static void main(String[] args) {
//今天是今年的第几天
//创建日历对象
Calendar instance = Calendar.getInstance();
System.out.println("年:"+instance.get(Calendar.YEAR));
System.out.println("月:"+(instance.get(Calendar.MONTH)+1));
System.out.println("日:"+instance.get(Calendar.DATE));
System.out.println("天数:"+instance.get(Calendar.DAY_OF_YEAR));
}
}
问题:计算距2027.07.01还有多少天
package com.ffyc;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateDemo05 {
public static void main(String[] args) throws ParseException {
Date today = new Date();
long t1 = today.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date otherDay = sdf.parse("2027-07-01");
long t2 = otherDay.getTime();
double day = ((t2-t1)/1000.0/60/60/24);
System.out.println("day:"+Math.ceil(day));
//同一年计算
//Calendar c = Calendar.getInstance();
//int a = c.get(Calendar.DAY_OF_YEAR);
//c.set(2024,7,1);
//int b = c.get(Calendar.DAY_OF_YEAR);
//System.out.println(b-a);
}
}