一,如何创建时间对象
- 利用空参构造创建的对象,默认表示系统的当前时间
- 利用有参构造创建的对象,表示指定的时间
public class Demo {
public static void main(String[] args) {
Date d1 = new Date();
System.out.println(d1);
Date d2 = new Date(0L);
System.out.println(d2);
d2.setTime(1000l); //1000K毫秒是1秒
System.out.println(d2);
}
}
Mon May 13 10:08:55 CST 2024
Thu Jan 01 08:00:00 CST 1970
Thu Jan 01 08:00:01 CST 1970
d1表示的是现在的时间,Mon星期一,May5月,2024年
d2表示的是事件原点,0L表示距时间原点0毫秒,接着setTime()修改时间,多增加1000L,即1秒。
二,修改和获取时间对象的毫秒值
setTime(毫秒值);
getTime();获得的是时间的毫秒值
三,SimpleDateFormat
1.作用
格式化:把时间变成用户喜欢的格式
解析:把字符串表示的时间变成Date对象
2.构造方法
public SimpleDateFormat(); //构造一个SimpleDateFormat,使用默认格式
public SimpleDateFormat(); //使用的是指定格式
3.常用方法
public final String format(Date date); //格式化:(日期对象—>字符串)
public Date parse(String source); //解析:(字符串—>日期对象)
它用预定义的字符串表示格式化:
- yyyy:年
- MM:月
- dd: 日
- HH: 小时
- mm: 分钟
- ss: 秒
public class Demo {
public static void main(String[] args) {
//1.先获取一个时间
Date date = new Date();//获取当前时间
SimpleDateFormat sdf1 = new SimpleDateFormat();
var sdf2 = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss");
String dateString = sdf1.format(date);
System.out.println(dateString);
System.out.println(sdf2.format(date));
}
}
2024/5/13 10:58
2024_05_13 10:58:22
分析:
- 先获取一个时间,空参有参都可以
- 规定格式:SimpleDateFormat sdf = new SimpleDateFormat();可以自己规定可以默认
- format输出的是一个String类型
- sdf(格式).format(date);
public class Demo {
public static void main(String[] args) {
//1.先获取一个时间
Date date = new Date();//获取当前时间
var sdf2 = new SimpleDateFormat("E yyyy_MM_dd HH:mm:ss");
System.out.println(sdf2.format(date));
}
}
周一 2024_05_13 11:09:44
E表示周一
一般来说,字母越长,输出越长