在完成对C语言的学习后,我最近开始了对C++和Java的学习,目前跟着视频学习了一些语法,也跟着敲了一些代码,有了一定的掌握程度。现在将跟着视频做的笔记进行整理。本篇博客是整理Java知识点的第十六篇博客。
本篇博客介绍了Java的日期相关类和异常。
本系列博客所有Java代码都使用IntelliJ IDEA编译运行,版本为2022.1。所用JDK版本为JDK11。
目录
Date类有关于时间的一些工具,使用Date类需要导包,import java.util.Date。
Date类的构造函数可以接收一个参数,单位是毫秒。
- import java.util.Date;
- public class datetest1 {
- public static void main(String[] args){
- Date date1 = new Date();
- System.out.println(date1);
-
- long date = 1000*60*60*24;
- Date date2 = new Date(date*366*50);
- System.out.println(date2);
- }
- }
程序创建了两个Date类对象date1和date2,date2有参数。程序的输出是:
Mon Aug 15 20:46:01 CST 2022
Sat Feb 08 08:00:00 CST 2020
第一行输出应该是当前时间。
public long getTime()获取1970年1月1日0时0分0秒以来到现在的毫秒值。
public void setTime(long time)设置时间,单位是毫秒。
- import java.util.Date;
- public class datetest2 {
- public static void main(String[] args){
- Date d = new Date();
- System.out.println(d);
- System.out.println(d.getTime()*1.0/1000/60/60/24/365.25);
-
- int time = 1000*60*60*24;
- d.setTime(time);
- System.out.println(d);
- }
- }
程序的输出是:
Mon Aug 15 20:49:16 CST 2022
52.62021689105001
Fri Jan 02 08:00:00 CST 1970
SimpleDateFormat类用于格式化和解析日期。使用此类需要导包,import java.text.SimpleDateFormat。
日期和时间格式由日期和时间模式字符串指定,在日期和时间模式字符串中,字母表示模式字母。
常用的是:y表示年,M表示月,d表示日,H表示时,m表示分,s表示秒。
public SimpleDateFormat()构造一个类对象,使用默认模式和日期格式。
public SimpleDateFormat(String pattern)构造一个类对象,使用参数pattern的格式。
public final String format(Date date)将日期格式化为日期字符串。
public Date parse(String source)从给定字符串开始解析文本以生成Date类对象。
- import java.text.ParseException;
- import java.util.Date;
- import java.text.SimpleDateFormat;
- public class simpledateformat {
- public static void main(String[] args) throws ParseException {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- Date d = new Date();
- String s1 = sdf.format(d);
- System.out.println(s1);
-
- String s2 = "2021/06/09 12:15:00";
- d = sdf.parse(s2);
- System.out.println(d);
- }
- }
程序中遇到代码提示会出现异常,就抛出异常。
SimpleDateFormat类按照参数的格式创建了一个SimpleDateFormat类对象sdf。
程序的输出是:
2022/08/15 20:57:42
Wed Jun 09 12:15:00 CST 2021
可以利用Date和SimpleDateFormat类制作一个很简易的日期工具类。
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- public class datetool {
- public static String datetostring(Date d,String s){
- SimpleDateFormat sdf = new SimpleDateFormat(s);
- String result = sdf.format(d);
- return result;
- }
-
- public static Date stringtodate(String s,String std) throws ParseException {
- SimpleDateFormat sdf = new SimpleDateFormat(std);
- Date d = sdf.parse(s);
- return d;
- }
- }
datetool类的datetostring静态方法接受一个Date类对象d,和一个字符串s,利用SimpleDateFormat类的format方法得到字符串,并将其返回。另一个静态方法stringtodate有两个参数s和std,利用std为参数创建一个SimpleDateFormat类对象,并利用parse方法得到Date类对象d,返回d。
- import java.text.ParseException;
- import java.util.Date;
- public class datettooltest {
- public static void main(String[] args) throws ParseException {
- Date d = new Date();
- String s = datetool.datetostring(d,"yyyy/MM/dd HH:mm:ss");
- System.out.println(s);
-
- String stest = "2021/09/11 08:30:00";
- d = datetool.stringtodate(stest,"yyyy/MM/dd HH:mm:ss");
- System.out.println(d);
- }
- }
datetooltest类测试了datetool类。因为都是静态方法,所以不创建具体对象。
程序的输出是:
2022/08/15 21:05:14
Sat Sep 11 08:30:00 CST 2021
Calendar类为某一时刻和某一组日历字段之间的转换,以及操作日历字段提供了一些方法。使用Calendar类需要导包,import java.util.Calendar。
Calendar类的类方法getInstance用于获取Calendar对象,其日历字段已使用当前时间和日期初始化。getInstance方法的方法头是 public static Calendar getInstance()。
- import java.util.Calendar;
- public class calendartest1 {
- public static void main(String[] args){
- Calendar c = Calendar.getInstance();
- int year = c.get(Calendar.YEAR);
- int month = c.get(Calendar.MONTH) + 1;
- int date = c.get(Calendar.DATE);
-
- System.out.println("The year is " + year);
- System.out.println("The month is " + month);
- System.out.println("The date is " + date);
- }
- }
Calendar类的get(Calendar.YEAR)获取当前年份,get(Calendar.MONTH)获取当前月份(但是从零开始,实际月份需要加一),get(Calendar.DATE)获取当前日期。
程序的输出是:
The year is 2022
The month is 8
The date is 15
public int get(int field)返回给定日历字段的值。
public abstract void add(int field,int amount)根据日历的规则,将指定的时间量加或减给定的日历字段。
public final void set(int year,int month,int date)设置当前年月日。
- import java.util.Calendar;
- public class calendartest2 {
- public static void main(String[] args){
- Calendar c = Calendar.getInstance();
- int year = c.get(Calendar.YEAR);
- int month = c.get(Calendar.MONTH) + 1;
- int date = c.get(Calendar.DATE);
- System.out.println("The year is " + year);
- System.out.println("The month is " + month);
- System.out.println("The date is " + date);
-
- c.add(Calendar.YEAR, -3);
- c.add(Calendar.MONTH,5);
- c.add(Calendar.DATE,20);
- year = c.get(Calendar.YEAR);
- month = c.get(Calendar.MONTH) + 1;
- date = c.get(Calendar.DATE);
- System.out.println("The year is " + year);
- System.out.println("The month is " + month);
- System.out.println("The date is " + date);
-
- c.set(2021,5,9);
- year = c.get(Calendar.YEAR);
- month = c.get(Calendar.MONTH) + 1;
- date = c.get(Calendar.DATE);
- System.out.println("The year is " + year);
- System.out.println("The month is " + month);
- System.out.println("The date is " + date);
- }
- }
这段代码利用了相关方法。程序的输出是:
The year is 2022
The month is 8
The date is 15
The year is 2020
The month is 2
The date is 4
The year is 2021
The month is 6
The date is 9
- import java.util.Scanner;
- import java.util.Calendar;
- public class calendartest3 {
- public static void main(String[] args){
- Scanner sc = new Scanner(System.in);
- Calendar c = Calendar.getInstance();
-
- int year;
- System.out.print("Please enter the year");
- year = sc.nextInt();
- int month = 2;
- int day = 1;
- c.set(year,month,day);
-
- c.add(Calendar.DATE, -1);
- day = c.get(Calendar.DATE);
- System.out.println(day);
- }
- }
程序利用Calendar类来获取天数,要求输入年份,随后将这一年的3月1日设置为对象的值,再利用日期减一得到二月的最后一天。
输入2022后的结果:
Please enter the year2022
28
输入2020后的结果:
Please enter the year2020
29
异常就是程序出现了不正常的情况。
Throwable是最大的异常,下面包括Error和Exception,Exception分为RuntimeException和非RuntimeException。
Error是严重问题,不需要处理。
Exception称为异常类,表示程序本身可以处理的问题。
RuntimeException在编译期间不检查,出现问题后需要回来修改代码。
非RuntimeException在编译期间必须处理,否则无法通过编译。
如果程序出现了问题,且没有做出任何处理,JVM会进行默认处理。把异常的名称,原因,出现位置输出在控制台,随后结束程序。
try...catch...语句的格式是:
try{
可能出现异常的代码
} catch(异常类名 变量名){
异常的处理代码
}
程序从try里面的代码开始执行,出现异常会生成异常类对象,该对象被交给Java运行时系统。Java运行时系统收到异常对象时,到catch中查找匹配的异常类,找到就进行处理。这样执行完毕后程序还可以继续向下执行。
- public class trycatch {
- public static void main(String[] args){
- System.out.println("Begin");
- method();
- System.out.println("End");
- }
-
- public static void method(){
- try {
- int[] arr = new int[]{1, 2, 3};
- System.out.println(arr[3]);
- }catch(ArrayIndexOutOfBoundsException aioobe){
- aioobe.printStackTrace();
- }
- }
- }
这段代码的method方法利用了try...catch...语句。try语句里定义了一个含有三个元素的数组,要求输出索引为3的元素,显然发生了数组越界。catch语句里是对应的处理。下面是程序的输出:
Begin
End
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at trycatch.method(trycatch.java:11)
at trycatch.main(trycatch.java:4)
程序并没有在出现错误时就结束。
public String getMessage()返回此Throwable的详细消息字符串。
public String toString()返回此可能的简短描述。
public void printStackTrace()把异常的错误信息输出。
- public class throwable {
- public static void main(String[] args){
- System.out.println("Begin");
- method();
- System.out.println("End");
- }
-
- public static void method(){
- try {
- int[] arr = new int[]{1, 2, 3};
- System.out.println(arr[3]);
- }catch(ArrayIndexOutOfBoundsException aioobe){
- System.out.println(aioobe.toString());
- System.out.println(aioobe.getMessage());
- aioobe.printStackTrace();
- }
- }
- }
这段代码和错误和上面的一样。程序的输出是:
Begin
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Index 3 out of bounds for length 3
End
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at throwable.method(throwable.java:11)
at throwable.main(throwable.java:4)
Java的异常分为两大类,编译时异常和运行时异常。编译时异常必须显示处理,否则无法通过编译。运行时异常无需显示处理。
- import java.text.ParseException;
- import java.util.Date;
- import java.text.SimpleDateFormat;
- public class difference {
- public static void main(String[] args){
- System.out.println("Begin");
- method1();
- method2();
- System.out.println("End");
- }
-
- public static void method1(){
- try {
- int[] arr = new int[]{1, 2, 3};
- System.out.println(arr[0]);
- }catch(ArrayIndexOutOfBoundsException aioobe){
- aioobe.printStackTrace();
- }
- }
-
- public static void method2(){
- try {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- String s = "2021/06/09 12/15/00";
- Date d = sdf.parse(s);
- System.out.println(d);
- } catch(ParseException pe){
- pe.printStackTrace();
- }
- }
- }
method1方法容易数组越界,method2方法出现了格式错误。
这段程序的输出是:
Begin
1
java.text.ParseException: Unparseable date: "2021/06/09 12/15/00"
at java.base/java.text.DateFormat.parse(DateFormat.java:395)
at difference.method2(difference.java:25)
at difference.main(difference.java:8)
End
try...catch...可以处理异常,但是有时候我们没有处理异常的权限。对于这种情况,Java提供了throws处理方案。格式是:
throws 异常类名
这个格式写在方法的括号后面。
编译时异常必须处理,如果用throws,则由调用方进行处理。运行时异常可以不处理,出现问题后修改代码。
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- public class throwstest {
- public static void main(String[] args) {
- System.out.println("Begin");
- method1();
- try {
- method2();
- } catch(ParseException pe){
- pe.printStackTrace();
- }
- System.out.println("End");
- }
-
- public static void method1() throws ArrayIndexOutOfBoundsException {
- int[] arr = new int[]{1, 2, 3};
- System.out.println(arr[0]);
- }
-
- public static void method2() throws ParseException{
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- String s = "2021/06/09 12/15/00";
- Date d = sdf.parse(s);
- System.out.println(d);
- }
- }
代码问题和上面一样,程序的输出是:
Begin
1
java.text.ParseException: Unparseable date: "2021/06/09 12/15/00"
at java.base/java.text.DateFormat.parse(DateFormat.java:395)
at throwstest.method2(throwstest.java:24)
at throwstest.main(throwstest.java:9)
End
method2方法中的错误由调用方main方法处理。
自定义异常的格式是:
public class 异常类名 extends Exception{
无参构造
带参构造
}
- public class throwtest extends Exception{
- public throwtest(){}
- public throwtest(String message){
- super(message);
- }
- }
这是一个例子。
在方法体内用throw 异常对象名可以抛出异常。执行throw表示一定出现了异常。
- public class teacherscore {
- public void judge(int score) throws throwtest {
- if(score < 0||score > 100){
- throw new throwtest("It is beyond the range");
- }else{
- System.out.println("It is in the range");
- }
- }
- }
此类中score大于100或小于0会抛出异常。
- import java.util.Scanner;
- public class teachertest {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int score;
- System.out.print("Please enter the score");
- score = sc.nextInt();
-
- teacherscore ts = new teacherscore();
- try {
- ts.judge(score);
- } catch (throwtest e) {
- e.printStackTrace();
- }
- }
- }
这是运行代码,要求输入分数。随后调用teacherscore类对象的judge方法。
程序输入120的结果
Please enter the score120
throwtest: It is beyond the range
at teacherscore.judge(teacherscore.java:4)
at teachertest.main(teachertest.java:11)
程序输入80的结果
Please enter the score80
It is in the range