1.1 Date類
-
計算機中時間原點
1970年1月1日 00:00:00
-
時間換算單位
1秒 = 1000毫秒
-
Date類概述
Date 代表了一個特定的時間,精確到毫秒
-
方法名 說明 public Date() 分配一個 Date對象,並初始化,以便它代表它被分配的時間,精確到毫秒 public Date(long date) 分配一個 Date對象,並將其初始化為表示從標准基准時間起指定的毫秒數 -
示例代碼
public class DateDemo01 {
public static void main(String[] args) {
//public Date():分配一個 Date對象,並初始化,以便它代表它被分配的時間,精確到毫秒
Date d1 = new Date();
System.out.println(d1);
//public Date(long date):分配一個 Date對象,並將其初始化為表示從標准基准時間起指定的毫秒數
long date = 1000*60*60;
Date d2 = new Date(date);
System.out.println(d2);
}
}
1.2 Date類常用方法(重點)
-
常用方法
方法名 說明 public long getTime() 獲取的是日期對象從1970年1月1日 00:00:00到現在的毫秒值 public void setTime(long time) 設置時間,給的是毫秒值 -
示例代碼
public class DateDemo02 {
public static void main(String[] args) {
//創建日期對象
Date d = new Date();
//public long getTime():獲取的是日期對象從1970年1月1日 00:00:00到現在的毫秒值
// System.out.println(d.getTime());
// System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");
//public void setTime(long time):設置時間,給的是毫秒值
// long time = 1000*60*60;
long time = System.currentTimeMillis();
d.setTime(time);
System.out.println(d);
}
}
1.3 SimpleDateFormat類(重點)
-
SimpleDateFormat類概述
SimpleDateFormat是一個具體的類,用於以區域設置敏感的方式格式化和解析日期。
我們重點學習日期格式化和解析
-
SimpleDateFormat類構造方法
方法名 說明 public SimpleDateFormat() 構造一個SimpleDateFormat,使用默認模式和日期格式 public SimpleDateFormat(String pattern) 構造一個SimpleDateFormat使用給定的模式和默認的日期格式 -
SimpleDateFormat類的常用方法
-
格式化(從Date到String)
-
public final String format(Date date):將日期格式化成日期/時間字符串
-
-
解析(從String到Date)
-
public Date parse(String source):從給定字符串的開始解析文本以生成日期
-
-
-
示例代碼
public class SimpleDateFormatDemo {
public static void main(String[] args) throws ParseException {
//格式化:從 Date 到 String
Date d = new Date();
// SimpleDateFormat sdf = new SimpleDateFormat();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String s = sdf.format(d);
System.out.println(s);
System.out.println("--------");
//從 String 到 Date
String ss = "2048-08-09 11:11:11";
//ParseException
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dd = sdf2.parse(ss);
System.out.println(dd);
}
}
1.4 時間日期類練習
-
需求
秒殺開始時間是2020年11月11日 00:00:00,結束時間是2020年11月11日 00:10:00,用戶小賈下單時間是2020年11月11日 00:03:47,用戶小皮下單時間是2020年11月11日 00:10:11,判斷用戶有沒有成功參與秒殺活動
-
實現步驟
-
判斷下單時間是否在開始到結束的范圍內
-
把字符串形式的時間變成毫秒值
-
-
代碼實現
public class DateDemo5 {
public static void main(String[] args) throws ParseException {
//開始時間:2020年11月11日 0:0:0
//結束時間:2020年11月11日 0:10:0
//小賈2020年11月11日 0:03:47
//小皮2020年11月11日 0:10:11
//1.判斷兩位同學的下單時間是否在范圍之內就可以了。
//2.要把每一個時間都換算成毫秒值。
String start = "2020年11月11日 0:0:0";
String end = "2020年11月11日 0:10:0";
String jia = "2020年11月11日 0:03:47";
String pi = "2020年11月11日 0:10:11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
long startTime = sdf.parse(start).getTime();
long endTime = sdf.parse(end).getTime();
// System.out.println(startTime);
// System.out.println(endTime);
long jiaTime = sdf.parse(jia).getTime();
long piTime = sdf.parse(pi).getTime();
if(jiaTime >= startTime && jiaTime <= endTime){
System.out.println("小賈同學參加上了秒殺活動");
}else{
System.out.println("小賈同學沒有參加上秒殺活動");
}
System.out.println("------------------------");
if(piTime >= startTime && piTime <= endTime){
System.out.println("小皮同學參加上了秒殺活動");
}else{
System.out.println("小皮同學沒有參加上秒殺活動");
}
}
}
2.JDK8時間日期類 (重點)
2.1 JDK8新增日期類
-
LocalDate 表示日期(年月日)
-
LocalTime 表示時間(時分秒)
-
LocalDateTime 表示時間+ 日期 (年月日時分秒)
2.2 LocalDateTime創建方法
-
方法說明
方法名 說明 public static LocalDateTime now() 獲取當前系統時間 public static LocalDateTime of (年, 月 , 日, 時, 分, 秒) 使用指定年月日和時分秒初始化一個LocalDateTime對象 -
示例代碼
public class JDK8DateDemo2 {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 11);
System.out.println(localDateTime);
}
}
2.3 LocalDateTime獲取方法
-
方法說明
方法名 說明 public int getYear() 獲取年 public int getMonthValue() 獲取月份(1-12) public int getDayOfMonth() 獲取月份中的第幾天(1-31) public int getDayOfYear() 獲取一年中的第幾天(1-366) public DayOfWeek getDayOfWeek() 獲取星期 public int getMinute() 獲取分鍾 public int getHour() 獲取小時 -
示例代碼
public class JDK8DateDemo3 {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 20);
//public int getYear() 獲取年
int year = localDateTime.getYear();
System.out.println("年為" +year);
//public int getMonthValue() 獲取月份(1-12)
int month = localDateTime.getMonthValue();
System.out.println("月份為" + month);
Month month1 = localDateTime.getMonth();
// System.out.println(month1);
//public int getDayOfMonth() 獲取月份中的第幾天(1-31)
int day = localDateTime.getDayOfMonth();
System.out.println("日期為" + day);
//public int getDayOfYear() 獲取一年中的第幾天(1-366)
int dayOfYear = localDateTime.getDayOfYear();
System.out.println("這是一年中的第" + dayOfYear + "天");
//public DayOfWeek getDayOfWeek()獲取星期
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
System.out.println("星期為" + dayOfWeek);
//public int getMinute() 獲取分鍾
int minute = localDateTime.getMinute();
System.out.println("分鍾為" + minute);
//public int getHour() 獲取小時
int hour = localDateTime.getHour();
System.out.println("小時為" + hour);
}
}
2.4 LocalDateTime轉換方法
-
方法說明
方法名 說明 public LocalDate toLocalDate () 轉換成為一個LocalDate對象 public LocalTime toLocalTime () 轉換成為一個LocalTime對象 -
示例代碼
public class JDK8DateDemo4 {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.of(2020, 12, 12, 8, 10, 12);
//public LocalDate toLocalDate () 轉換成為一個LocalDate對象
LocalDate localDate = localDateTime.toLocalDate();
System.out.println(localDate);
//public LocalTime toLocalTime () 轉換成為一個LocalTime對象
LocalTime localTime = localDateTime.toLocalTime();
System.out.println(localTime);
}
}
2.5 LocalDateTime格式化和解析
-
方法說明
方法名 說明 public String format (指定格式) 把一個LocalDateTime格式化成為一個字符串 public LocalDateTime parse (准備解析的字符串, 解析格式) 把一個日期字符串解析成為一個LocalDateTime對象 public static DateTimeFormatter ofPattern(String pattern) 使用指定的日期模板獲取一個日期格式化器DateTimeFormatter對象 -
示例代碼
public class JDK8DateDemo5 {
public static void main(String[] args) {
//method1();
//method2();
}
private static void method2() {
//public static LocalDateTime parse (准備解析的字符串, 解析格式) 把一個日期字符串解析成為一個LocalDateTime對象
String s = "2020年11月12日 13:14:15";
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse(s, pattern);
System.out.println(parse);
}
private static void method1() {
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 12, 13, 14, 15);
System.out.println(localDateTime);
//public String format (指定格式) 把一個LocalDateTime格式化成為一個字符串
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
String s = localDateTime.format(pattern);
System.out.println(s);
}
}
2.6 LocalDateTime增加或者減少時間的方法
-
方法說明
方法名 說明 public LocalDateTime plusYears (long years) 添加或者減去年 public LocalDateTime plusMonths(long months) 添加或者減去月 public LocalDateTime plusDays(long days) 添加或者減去日 public LocalDateTime plusHours(long hours) 添加或者減去時 public LocalDateTime plusMinutes(long minutes) 添加或者減去分 public LocalDateTime plusSeconds(long seconds) 添加或者減去秒 public LocalDateTime plusWeeks(long weeks) 添加或者減去周 -
示例代碼
/**
* JDK8 時間類添加或者減去時間的方法
*/
public class JDK8DateDemo6 {
public static void main(String[] args) {
//public LocalDateTime plusYears (long years) 添加或者減去年
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
//LocalDateTime newLocalDateTime = localDateTime.plusYears(1);
//System.out.println(newLocalDateTime);
LocalDateTime newLocalDateTime = localDateTime.plusYears(-1);
System.out.println(newLocalDateTime);
}
}
2.7 LocalDateTime減少或者增加時間的方法
-
方法說明
方法名 說明 public LocalDateTime minusYears (long years) 減去或者添加年 public LocalDateTime minusMonths(long months) 減去或者添加月 public LocalDateTime minusDays(long days) 減去或者添加日 public LocalDateTime minusHours(long hours) 減去或者添加時 public LocalDateTime minusMinutes(long minutes) 減去或者添加分 public LocalDateTime minusSeconds(long seconds) 減去或者添加秒 public LocalDateTime minusWeeks(long weeks) 減去或者添加周 -
示例代碼
/**
* JDK8 時間類減少或者添加時間的方法
*/
public class JDK8DateDemo7 {
public static void main(String[] args) {
//public LocalDateTime minusYears (long years) 減去或者添加年
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
//LocalDateTime newLocalDateTime = localDateTime.minusYears(1);
//System.out.println(newLocalDateTime);
LocalDateTime newLocalDateTime = localDateTime.minusYears(-1);
System.out.println(newLocalDateTime);
}
}
2.8 LocalDateTime修改方法
-
方法說明
方法名 說明 public LocalDateTime withYear(int year) 直接修改年 public LocalDateTime withMonth(int month) 直接修改月 public LocalDateTime withDayOfMonth(int dayofmonth) 直接修改日期(一個月中的第幾天) public LocalDateTime withDayOfYear(int dayOfYear) 直接修改日期(一年中的第幾天) public LocalDateTime withHour(int hour) 直接修改小時 public LocalDateTime withMinute(int minute) 直接修改分鍾 public LocalDateTime withSecond(int second) 直接修改秒 -
示例代碼
/**
* JDK8 時間類修改時間
*/
public class JDK8DateDemo8 {
public static void main(String[] args) {
//public LocalDateTime withYear(int year) 修改年
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
// LocalDateTime newLocalDateTime = localDateTime.withYear(2048);
// System.out.println(newLocalDateTime);
LocalDateTime newLocalDateTime = localDateTime.withMonth(20);
System.out.println(newLocalDateTime);
}
}
2.9 Period
-
方法說明
方法名 說明 public static Period between(開始時間,結束時間) 計算兩個“時間"的間隔 public int getYears() 獲得這段時間的年數 public int getMonths() 獲得此期間的總月數 public int getDays() 獲得此期間的天數 public long toTotalMonths() 獲取此期間的總月數 -
示例代碼
/**
* 計算兩個時間的間隔
*/
public class JDK8DateDemo9 {
public static void main(String[] args) {
//public static Period between(開始時間,結束時間) 計算兩個"時間"的間隔
LocalDate localDate1 = LocalDate.of(2020, 1, 1);
LocalDate localDate2 = LocalDate.of(2048, 12, 12);
Period period = Period.between(localDate1, localDate2);
System.out.println(period);//P28Y11M11D
//public int getYears() 獲得這段時間的年數
System.out.println(period.getYears());//28
//public int getMonths() 獲得此期間的月數
System.out.println(period.getMonths());//11
//public int getDays() 獲得此期間的天數
System.out.println(period.getDays());//11
//public long toTotalMonths() 獲取此期間的總月數
System.out.println(period.toTotalMonths());//347
}
}
2.10 Duration
-
方法說明
方法名 說明 public static Durationbetween(開始時間,結束時間) 計算兩個“時間"的間隔 public long toSeconds() 獲得此時間間隔的秒 public int toMillis() 獲得此時間間隔的毫秒 public int toNanos() 獲得此時間間隔的納秒 -
示例代碼
/**
* 計算兩個時間的間隔
*/
public class JDK8DateDemo10 {
public static void main(String[] args) {
//public static Duration between(開始時間,結束時間) 計算兩個“時間"的間隔
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 1, 1, 13, 14, 15);
LocalDateTime localDateTime2 = LocalDateTime.of(2020, 1, 2, 11, 12, 13);
Duration duration = Duration.between(localDateTime1, localDateTime2);
System.out.println(duration);//PT21H57M58S
//public long toSeconds() 獲得此時間間隔的秒
System.out.println(duration.toSeconds());//79078
//public int toMillis() 獲得此時間間隔的毫秒
System.out.println(duration.toMillis());//79078000
//public int toNanos() 獲得此時間間隔的納秒
System.out.println(duration.toNanos());//79078000000000
}
}
3.異常
3.1 異常
-
異常的概述
異常就是程序出現了不正常的情況
-
異常的體系結構
3.2 編譯時異常和運行時異常的區別
-
編譯時異常
-
都是Exception類及其子類
-
必須顯示處理,否則程序就會發生錯誤,無法通過編譯
-
-
運行時異常
-
都是RuntimeException類及其子類
-
無需顯示處理,也可以和編譯時異常一樣處理
-
-
3.3 throws方式處理異常
-
定義格式
public void 方法() throws 異常類名 {
} -
示例代碼
public class ExceptionDemo {
public static void main(String[] args) throws ParseException{
System.out.println("開始");
// method();
method2();
System.out.println("結束");
}
//編譯時異常
public static void method2() throws ParseException {
String s = "2048-08-09";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse(s);
System.out.println(d);
}
//運行時異常
public static void method() throws ArrayIndexOutOfBoundsException {
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
}
} -
注意事項
-
這個throws格式是跟在方法的括號后面的
-
編譯時異常必須要進行處理,兩種處理方案:try...catch …或者 throws,如果采用 throws 這種方案,在方法上進行顯示聲明,將來誰調用這個方法誰處理
-
運行時異常因為在運行時才會發生,所以在方法后面可以不寫,運行時出現異常默認交給jvm處理
-
3.6 throw拋出異常
-
格式
throw new 異常();
-
注意
這個格式是在方法內的,表示當前代碼手動拋出一個異常,下面的代碼不用再執行了
-
throws和throw的區別
throws throw 用在方法聲明后面,跟的是異常類名 用在方法體內,跟的是異常對象名 表示聲明異常,調用該方法有可能會出現這樣的異常 表示手動拋出異常對象,由方法體內的語句處理 -
示例代碼
public class ExceptionDemo8 {
public static void main(String[] args) {
//int [] arr = {1,2,3,4,5};
int [] arr = null;
printArr(arr);//就會 接收到一個異常.
//我們還需要自己處理一下異常.
}
private static void printArr(int[] arr) {
if(arr == null){
//調用者知道成功打印了嗎?
//System.out.println("參數不能為null");
throw new NullPointerException(); //當參數為null的時候
//手動創建了一個異常對象,拋給了調用者,產生了一個異常
}else{
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
}
3.7 try-catch方式處理異常(重點)
-
定義格式
try {
可能出現異常的代碼;
} catch(異常類名 變量名) {
異常的處理代碼;
} -
執行流程
-
程序從 try 里面的代碼開始執行
-
出現異常,就會跳轉到對應的 catch 里面去執行
-
執行完畢之后,程序還可以繼續往下執行
-
-
示例代碼
public class ExceptionDemo01 {
public static void main(String[] args) {
System.out.println("開始");
method();
System.out.println("結束");
}
public static void method() {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
System.out.println("這里能夠訪問到嗎");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("你訪問的數組索引不存在,請回去修改為正確的索引");
}
}
} -
注意
-
如果 try 中沒有遇到問題,怎么執行?
會把try中所有的代碼全部執行完畢,不會執行catch里面的代碼
-
如果 try 中遇到了問題,那么 try 下面的代碼還會執行嗎?
那么直接跳轉到對應的catch語句中,try下面的代碼就不會再執行了 當catch里面的語句全部執行完畢,表示整個體系全部執行完全,繼續執行下面的代碼
-
如果出現的問題沒有被捕獲,那么程序如何運行?
那么try...catch就相當於沒有寫.那么也就是自己沒有處理. 默認交給虛擬機處理.
-
同時有可能出現多個異常怎么處理?
出現多個異常,那么就寫多個catch就可以了. 注意點:如果多個異常之間存在子父類關系.那么父類一定要寫在下面
-
3.8 Throwable成員方法
-
常用方法
方法名 說明 public String getMessage() 返回此 throwable 的詳細消息字符串 public String toString() 返回此可拋出的簡短描述 public void printStackTrace() 把異常的錯誤信息輸出在控制台 -
示例代碼
public class ExceptionDemo02 {
public static void main(String[] args) {
System.out.println("開始");
method();
System.out.println("結束");
}
public static void method() {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[3]); //new ArrayIndexOutOfBoundsException();
System.out.println("這里能夠訪問到嗎");
} catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException();
// e.printStackTrace();
//public String getMessage():返回此 throwable 的詳細消息字符串
// System.out.println(e.getMessage());
//Index 3 out of bounds for length 3
//public String toString():返回此可拋出的簡短描述
// System.out.println(e.toString());
//java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
//public void printStackTrace():把異常的錯誤信息輸出在控制台
e.printStackTrace();
// java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
// at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18)
// at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11)
}
}
}
3.9 異常的練習
-
需求
鍵盤錄入學生的姓名和年齡,其中年齡為18 - 25歲,超出這個范圍是異常數據不能賦值.需要重新錄入,一直錄到正確為止
-
實現步驟
-
創建學生對象
-
鍵盤錄入姓名和年齡,並賦值給學生對象
-
如果是非法數據就再次錄入
-
-
代碼實現
學生類
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age >= 18 && age <= 25){
this.age = age;
}else{
//當年齡不合法時,產生一個異常
throw new RuntimeException("年齡超出了范圍");
}
}
測試類
public class ExceptionDemo12 {
public static void main(String[] args) {
// 鍵盤錄入學生的姓名和年齡,其中年齡為 18 - 25歲,
// 超出這個范圍是異常數據不能賦值.需要重新錄入,一直錄到正確為止。
Student s = new Student();
Scanner sc = new Scanner(System.in);
System.out.println("請輸入姓名");
String name = sc.nextLine();
s.setName(name);
while(true){
System.out.println("請輸入年齡");
String ageStr = sc.nextLine();
try {
int age = Integer.parseInt(ageStr);
s.setAge(age);
break;
} catch (NumberFormatException e) {
System.out.println("請輸入一個整數");
continue;
} catch (AgeOutOfBoundsException e) {
System.out.println(e.toString());
System.out.println("請輸入一個符合范圍的年齡");
continue;
}
/*if(age >= 18 && age <=25){
s.setAge(age);
break;
}else{
System.out.println("請輸入符合要求的年齡");
continue;
}*/
}
System.out.println(s);
}
}
3.10 自定義異常
-
自定義異常概述
當Java中提供的異常不能滿足我們的需求時,我們可以自定義異常
-
實現步驟
-
定義異常類
-
寫繼承關系
-
提供空參構造
-
提供帶參構造
-
-
代碼實現
異常類
public class AgeOutOfBoundsException extends RuntimeException {
public AgeOutOfBoundsException() {
}
public AgeOutOfBoundsException(String message) {
super(message);
}
}學生類
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age >= 18 && age <= 25){
this.age = age;
}else{
//如果Java中提供的異常不能滿足我們的需求,我們可以使用自定義的異常
throw new AgeOutOfBoundsException("年齡超出了范圍");
}
}
測試類
public class ExceptionDemo12 {
public static void main(String[] args) {
// 鍵盤錄入學生的姓名和年齡,其中年齡為 18 - 25歲,
// 超出這個范圍是異常數據不能賦值.需要重新錄入,一直錄到正確為止。
Student s = new Student();
Scanner sc = new Scanner(System.in);
System.out.println("請輸入姓名");
String name = sc.nextLine();
s.setName(name);
while(true){
System.out.println("請輸入年齡");
String ageStr = sc.nextLine();
try {
int age = Integer.parseInt(ageStr);
s.setAge(age);
break;
} catch (NumberFormatException e) {
System.out.println("請輸入一個整數");
continue;
} catch (AgeOutOfBoundsException e) {
System.out.println(e.toString());
System.out.println("請輸入一個符合范圍的年齡");
continue;
}
/*if(age >= 18 && age <=25){
s.setAge(age);
break;
}else{
System.out.println("請輸入符合要求的年齡");
continue;
}*/
}
System.out.println(s);
}
} -