时间类型

其中java.util.Date是核心类,随着jdk的发展,其功能被削弱,由别的类分担。

1Date类及常用方法

构造方法:

public Date(long date) {

    fastTime = date;

}

含义:从1970-1-1 00:00:00开始加fastTime毫秒后对应的时间。

常用方法

(1compareTo(Date date)比较两个时间前后

如果大于参数时间,返回1;如果等于返回0;如果小于,返回-1

 

(2after(Date date)判断是否在某个时间后

如果大于参数时间,返回true;如果小于等于参数时间,返回false

 

3getTime():返回自 1970 1 1 00:00:00 以来此 Date 对象表示的毫秒数

 

2CalendarGregorianCalendar

Calendar字段:1~12月英文字段,周日到周一的英文字段

常用方法:

(1)设置日历:g.set(year, month, date, hourOfDay, minute);

setTime(Date date),将某个时间转化成日历

 

(2)日期计算:add(Calendar.MONTH/Calendar.YEAR, amount);

 

3DateFormatSimpleDateFormat

构造方法:

public SimpleDateFormat(String pattern){

    this(pattern, Locale.getDefault(Locale.Category.FORMAT));

}

时间类型

常用方法:

1format(Date d):将某个时间解析成字符串输出

DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date d = new Date(12321314323L);

String str = df.format(d);

System.out.println(str);//1970-05-23 10:35:14

 

2parse(String str):将某个字串转换成时间

String str2 = "1977-7-7";

DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");

try {

    Date d2 = df2.parse(str2);

    System.out.println(d2);

} catch (Exception e) {

    e.printStackTrace();

}

 

4、综合案例:简单日历

public class Test{

    public static void main(String[] args) {

        System.out.println("请输入日期(按照格式:2030-3-10)");

        Scanner scanner = new Scanner(System.in);

        String str_date = scanner.nextLine();

 

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {

            Date date = format.parse(str_date);

            Calendar calendar = new GregorianCalendar();

            calendar.setTime(date);//将某个时间类转化成日历类

            int day = calendar.get(Calendar.DATE);//得到输入时间所在的几号

            calendar.set(Calendar.DATE, 1);//将该日历设置为当月1

 

            //得到当月有多少天

            int maxDate = calendar.getActualMaximum(Calendar.DATE);

            System.out.println("\t\t\t\t\t\t");

 

            for(int i=1;i<calendar.get(Calendar.DAY_OF_WEEK);i++){

                System.out.print('\t');

            }

 

            for(int i=1;i<=maxDate;i++){

                if(i==day){

                System.out.print("*");

            }

            System.out.print(i+"\t");

            //得到当前日历是星期几

            int week = calendar.get(Calendar.DAY_OF_WEEK);

            if(week == Calendar.SATURDAY){

            System.out.print('\n');

        }

        calendar.add(Calendar.DATE, 1);//将当前日历加一天

        }

 

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

效果:

时间类型

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-14
  • 2021-05-26
  • 2021-09-13
猜你喜欢
  • 2021-09-09
  • 2021-12-19
  • 2021-04-26
  • 2021-10-25
  • 2022-02-13
  • 2021-09-12
  • 2022-12-23
相关资源
相似解决方案