s-day01-Calendar类计算时间和获取date操作
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
package com.inmind.calendar04;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
/*
|
||||
Date类大部分的功能都过时了,那么JDK提供了一个更好用的类辅助Date,Calendar类
|
||||
@@ -18,7 +20,19 @@ void set(int field, int value) 将给定的日历字段设置为给定的值。
|
||||
参数一:日历类固定的值
|
||||
参数二:修改后的值
|
||||
Date类操作时间必须传入毫秒值,日历类提供了直接操作年月日,时分秒的api
|
||||
-------------------------------------
|
||||
Calendar中的add方法
|
||||
能够对时间进行计算
|
||||
public abstract void add(int field, int amount) :根据日历的规则,为给定的日历字段添加或减去指定的时间量。
|
||||
|
||||
|
||||
field参数:
|
||||
指定的年月日常量
|
||||
amount参数:
|
||||
正数:增加
|
||||
负数:减少
|
||||
----------------------------------------------
|
||||
public Date getTime() :返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象。
|
||||
*/
|
||||
public class Demo07 {
|
||||
public static void main(String[] args) {
|
||||
@@ -34,6 +48,25 @@ public class Demo07 {
|
||||
calendar.set(Calendar.MONTH,5);
|
||||
calendar.set(Calendar.DAY_OF_MONTH,27);
|
||||
printCanlder(calendar);
|
||||
System.out.println("-------------操作日历的计算对应的时间--------------");
|
||||
//在当前的时间基础上,+2年
|
||||
calendar.add(Calendar.YEAR,2);
|
||||
//在当前的时间基础上,+10月
|
||||
calendar.add(Calendar.MONTH,10);
|
||||
//在当前的时间基础上,-10天
|
||||
calendar.add(Calendar.DAY_OF_MONTH,-10);
|
||||
printCanlder(calendar);
|
||||
System.out.println("---------将当前时间转为我们想看的格式年月日,时分秒--------");
|
||||
Date date = calendar.getTime();
|
||||
System.out.println(date);
|
||||
|
||||
/*
|
||||
创建一个格式化对象
|
||||
2025-03-16 15:50:37
|
||||
*/
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
|
||||
String dateStr = sdf.format(date);
|
||||
System.out.println(dateStr);
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user