Date类
Date类有util包下的和sql包下的,这里我们学习的是util包下的
sql包下的Date类是util包下Date类的子类
Date d1 = new Date(); //构造方法,分配当前所在的时间,d1 =2020.2.24.9:24
long date = 1000*60*60;
Date d2 = new Date(date); //分配从1970年0时0分到现在的时间,我们是中国的时区,相当于从1970年8时0分开始分配
//输出的d2应该是1970年9时0分
Date类的常用方法
public long getTime() //获取的是日期对象从1970.1.10时0分到现在的毫秒值
public void setTime(long time) //设置时间,传进去的是毫秒值,输出的时间是从1970.1.1 0时0分开始算起的(算的是传进去的毫秒值距离1970标准时间后应该对应处于的时间)
public static void main(String[] args) {
Date d = new Date();
// System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365); //输出50.18年
System.out.println(d); //输出现在的时间
long time = System.currentTimeMillis();
d.setTime(time);
System.out.println(d); //输出的也是现在的时间
}
SimpleDateFormat类
这个类用于格式化和解析日期,什么意思呢?就是用不同的大小写字母来代表了时间的概念,并且在程序中有效
- y —— 年
- M ——月
- d ——日
- H—— 时
- m ——分
- s ——秒
//构造方法:
public SimpleDateFormat() //构造一个SimpleDateFormat,使用默认模式和日期格式
public SimpleDateFormat(String pattern) //构造一个SimpleDateFormat使用给定的模式和默认的日期格式
//格式化使用的方法(从Date到String)
public final format (Date date) //将日期格式化为日期或时间的字符串
//解析方法(从String到Date)
public Date parse(String source) //从给定的字符串开始解析文本以生成日期
代码示例:
public static void main(String[] args) {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat();
String s = sdf.format(d);
System.out.println(s);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
String s1 = sdf2.format(d);
System.out.println(s1);
}
//输出:
2/24/20, 11:00 AM
2020年02月24日11时00分45秒
//从String到Date
String s2 = "2020-02-24 11:02:00";
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d2 = sdf3.parse(s2);
//输出:
Mon Feb 24 11:02:00 CST 2020
注意你格式化的格式一定要和String里面的格式匹配,比如里面是“-”,你就不能用“年月日”来代替,而也要用“-”,
而且空格格数也要对应
Calendar类
Calendar类提供了getInstance用于获取Calendar对象,其日历字段已使用当前日期和时间初始化
通过代码来理解这个类以及其中的功能:
import java.time.Year;
import java.util.Calendar;
public class CalendarDemo {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
System.out.println(year+"年"+month+"月"+date+"日");
}
}
//输出:
2020年1月24日
Calendar类的常用方法
| 方法名 | 说明 |
public int get(int field)
返回给定日历字段的值
public abstract void add(int field, int amount)
根据日历的规则,将指定的时间量添加或减去给定的日 历字段
public final void set(int year,int month,int date)
设置当前日历的年月日