
-
计算机中的起始时间
1970年1月1日 00:00:00
- Date代表类一个特定的时间,精确到毫秒
- Date构造方法
- public Date():创建一个Date对象,表示默认时间,电脑的当前时间
- public Date(long date):创建一个Date对象,从计算机的时间原点开始,过了指定毫秒的时间;中国处于东八区,所以打印出来的时间为1970年1月1日 08:00:00
- public long getTime():获取时间对象的毫秒值
public static void main(String[] args){
Date dete1 = new Date();
long time = date.getTime();
System.out.println(time);
// 结果:当前时间的毫秒值,与System.currentTimeMillis();相同
}
- public void setTime(long time):设置时间,传递毫秒值
Date date1 = new Date();
date1.setTime(0L);
System.out.println(date1);
// 结果:时间原点
2.1SimpleDateFormat类
- SimpleDateFormat可以对Date对象,进行格式化和解析
- 格式化:Date对象 ——> 2020年1月1日 0:0:0
- 解析: 2020年1月1日 0:0:0 ———> Date对象
- 2020-11-11 13:27:06 ——— yyyy-MM-dd HH:mm:ss
- 2020年11月11日 13:27:06 ——— yyyy年MM月dd日 HH:mm:ss
- SimpleDateFormat的构造方法
public SimpleDateFormat(); // 使用默认格式
public SimpleDateFormat(String pattern) // 使用指定格式
// 当前时间的Date对象
Date date = new Date();
// 创建日期格式
SimpleDateFormat sdf = new SimpleDateFotmat("yyyy年MM月dd日 HH:mm:ss");
String result1 = sdf.format(date);
System.out.println(result1);
- SimpleDateFormat成员方法
// SimpleDateFormat对象.format(Date对象),返回指定格式
// SimpleDateFormat对象.parse(String s),将指定String字符串按格式转化为Date类
public static void main(String[] args) throws ParseException{
String s = "2048-01-01";
SimpleDateFormat sdf = new SimpleDateFotmat("yyyy-MM-dd");
Date date = sdf.parse(s);
System.out.println(date);
}
2.2时间日期类练习
-
判断用户下单时间是否在规定的秒杀活动范围之内
开始时间:2020年11月11日 00:00:00
结束时间:2020年11月11日 00:10:00
用户A:2020年11月11日 00:03:47
用户B:2020年11月11日 00:10:11
String start = "2020年11月11日 00:00:00"; String end = "2020年11月11日 00:10:00"; String A = "2020年11月11日 00:03:47"; String B = "2020年11月11日 00:10:11"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss") long startTime = sdf.parse(start).getTime(); long endTime = sdf.parse(end).getTime(); long aTime = sdf.parse(A).getTime(); long bTime = sdf.parse(B).getTime(); if(aTime >= startTime && aTime <= endTime){ System.out.println("参加成功!"); } else{ System.out.println("超过时间,参加失败!"); } if(bTime >= startTime && bTime <= endTime){ System.out.println("参加成功!"); }else{ System.out.println("超出时间,参加失败!"); }
- JDK8之前对指定日期增加
String s = "2020年11月11日 00:00:00";
SimpleDateFormat sdf = new SimpleDateFotmat("yyyy年MM月dd日 HH:mm:ss");
// 将字符串转化为日期对象
Date date = sdf.parse(s);
// 将日期对象转化为当前时间毫秒值
long time = date.getTime();
// 将日期加一天
time = time + (1000 * 60 * 60 * 24);
// 将新时间放入新日期对象
Date newDate = new Date(time);
// 格式化新日期
String result = sdf.format(newDate);
System.out.println(result);
- JDK8指定日期增加
String s = "2020年11月11日 00:00:00";
DateTimeFormatter pattern = DateTimeFormatter.ofpattern("yyyy年MM月dd日 HH:mm:ss");
// 将字符串转化为LocalDateTime
LocalDateTime localDateTime = LocalDateTime.parse(s,pattern);
// 将日期增加一天
LocalDateTime newLocalDateTime = localDateTime.plusDays(1);
// 新日期格式化
String result = newLocalDateTime.format(pattern);
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)