一、日期与时间类
1.Date类
Date类对象代表系统当前时间;
/**
* Data类常用API
*/
public class DateDemo1 {
public static void main(String[] args) {
Date date = new Date();
//Fri Jul 22 21:06:12 CST 2022
System.out.println(date);
//效果一致,获取java起始到现在的时间毫秒值
long time = date.getTime();
System.out.println(time);
long time1 = System.currentTimeMillis();
System.out.println("================");
//1.当前时间
Date d1 = new Date();
System.out.println(d1);
//2.当前时间后一小时121s后
long time2 = d1.getTime();
time2+=(60 * 60 + 121) * 1000;
//3.时间毫秒值转为日期对象
Date d2 = new Date(time2);
System.out.println(d2);
/* Date d2 = new Date();
d2.setTime(time2);*/
}
}
2.SimpleDateFormat类
-
可以设置Date对象或时间毫秒的时间展示形式;
-
可以把字符串的时间形式解析成日期对象;
/**
* SimpleDateFormat类常用API
*/
public class SimpleDateFormatDemo {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);
/**
* yyyy 2022
* EEE 周几
* a 上午下午
*/
//1.格式化日期对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE a");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
String rs = sdf.format(d);
//2022-07-22 21:27:13 星期五 下午
System.out.println(rs);
String rs2 = sdf2.format(d);
//2022年07月22日 21:27:13 星期五 下午
System.out.println(rs2);
//2.格式化时间毫秒值
long l = System.currentTimeMillis();
String rs3 = sdf.format(l);
System.out.println(rs3);
}
}
/**
* SimpleDateFormat解析字符串:
* 拿到一个时间字符串,求两天14小时49分06秒后是什么时间
*/
public class SimpleDateFormatDemo2 {
public static void main(String[] args) throws ParseException {
//1.拿到时间
String dateStr = "2021年08月06日 11:11:11";
//2.字符串解析成日期对象,时间形式完全一致
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d = sdf.parse(dateStr);
//3.往后走后的时间,计算时采用L,int型计算,数据量可能越界
long time = d.getTime() + (2L*24*60*60 + 14*60*60 + 49*60 + 6 ) * 1000;
//4.格式化时间毫秒值
String rs = sdf.format(time);
System.out.println(rs);
}
}
/**
* SimpleDateFormat解析字符串:
* 秒杀活动
*/
public class SimpleDateFormatDemoTest {
public static void main(String[] args) throws ParseException {
String startTime = "2021-11-11 00:00:00";
String endTime = "2021-11-11 00:10:00";
String jiaTime = "2021-11-11 00:03:47";
String xpTime = "2021-11-11 00:10:11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
Date jiaDate = sdf.parse(jiaTime);
Date xpDate = sdf.parse(xpTime);
if (jiaDate.after(startDate) && jiaDate.before(endDate)){
System.out.println("小贾成功秒杀");
}else {
System.out.println("小贾失败了");
}
if (xpDate.after(startDate) && xpDate.before(endDate)){
System.out.println("小皮成功秒杀");
}else {
System.out.println("小皮失败了");
}
}
}
2.1设置的大小Y和y有区别吗?
-
new SimpleDateFormat("YYYY-MM-dd");
-
y 是Year, Y 表示的是Week year
-
Week year 意思是当天所在的周属于的年份,一周从周日开始,周六结束,只要本周跨年,那么这周就算入下一年。
-
正确写法应该是
-
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
2.2 补充:sql语句设置时间格式
语法: DATE_FORMAT(date,format) 其中,date 参数是合法的日期。format 规定日期/时间的输出格式。
date_format(#{param.countTime}, '%Y-%m-%d')
SELECT username,date_format(create_time,'%Y-%m-%d') FROM community.user;
DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p') --Dec 29 2008 11:45 PM
DATE_FORMAT(NOW(),'%m-%d-%Y') --12-29-2008
DATE_FORMAT(NOW(),'%d %b %y') --29 Dec 08
DATE_FORMAT(NOW(),'%d %b %Y %T:%f') --29 Dec 2008 16:25:46.635
3.Calendar类
-
代表日历对象;
-
抽象类,不能之间创建对象;
-
注意:Calendar是可变日期对象,修改后对本身时间产生变化
/**
* Calendar类
*/
public class CalendarDemo {
public static void main(String[] args) {
//1.拿到系统此刻日历对象
Calendar cal = Calendar.getInstance();
//firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=6,WEEK_OF_YEAR=30,WEEK_OF_MONTH=4,DAY_OF_MONTH=22
// ,DAY_OF_YEAR=203,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=58,SECOND=25
// ,MILLISECOND=962,ZONE_OFFSET=28800000,DST_OFFSET=0]
System.out.println(cal);
//2.获取日历某一字段
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int days = cal.get(Calendar.DAY_OF_YEAR);
System.out.println(year+"年"+month+"月"+days);
//3.修改日历某个字段信息;
cal.set(Calendar.HOUR,12);
//4.为某个字段增加、减少指定时间
//64天59分后
cal.add(Calendar.DAY_OF_YEAR,64);
cal.add(Calendar.MINUTE,59);
//5.拿到此刻日期对象
Date d = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String rs = sdf.format(d);
System.out.println(rs);
//6.拿到时间毫秒值
long timeInMillis = cal.getTimeInMillis();
System.out.println(timeInMillis);
}
}
二、JDK8新增日期类
-
LocalDate:只有日期
-
LocalTime:只有时间
-
LocalDateTime:日期和时间
-
Instant:时间戳
-
DateTimeFormatter:时间格式化和解析
-
Duration:计算时间间隔
-
Period:计算日期间隔
-
新API几乎全部是不变类型,不用担心被修改
1.LocalDate、LocalTime、LocalDateTime,类实例是不可变对象
/**
* LocalDate
*/
public class Demo01LocalDate {
public static void main(String[] args) {
LocalDate nowDate = LocalDate.now();
System.out.println(nowDate);
int year = nowDate.getYear();
int monthValue = nowDate.getMonthValue();
int dayOfYear = nowDate.getDayOfYear();
int dayOfMonth = nowDate.getDayOfMonth();
DayOfWeek dayOfWeek = nowDate.getDayOfWeek();
int dayOfWeekValue = dayOfWeek.getValue();
//指定日期拿对象
LocalDate myDate = LocalDate.of(1999, 02, 23);
System.out.println(myDate);
LocalDate myDate2 = LocalDate.of(1999, Month.FEBRUARY, 23);
}
}
/**
* LocalTime
*/
public class Demo02LocalTime {
public static void main(String[] args) {
LocalTime nowTime = LocalTime.now();
int hour = nowTime.getHour();
int minute = nowTime.getMinute();
int second = nowTime.getSecond();
//纳秒
int nano = nowTime.getNano();
LocalTime.of(8,20);
LocalTime.of(8,20,58);
LocalTime.of(8,20,58,150);
LocalTime localTime = LocalTime.of(8, 20, 58, 150);
//年月日 时分秒 纳秒
LocalDateTime localDateTime = LocalDateTime.of(1991, 11, 11, 11, 11, 11, 111);
LocalDateTime localDateTime2 = LocalDateTime.of(1991, Month.NOVEMBER, 11, 11, 11, 11, 111);
}
}
/**
* LocalDateTime
*/
public class Demo03LocalDateTime {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
int year = localDateTime.getYear();
/**
* 兼容前两者
*/
//兼容前两者,可以转换为前两者
LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();
}
}
/**
* UpdateTime
*/
public class Demo04UpdateTime {
public static void main(String[] args) {
//不可变对象,每次修改产生新对象
LocalTime localTime = LocalTime.now();
//一小时前;一分钟前,
localTime.minusHours(1);
localTime.minusMinutes(1);
localTime.minusSeconds(1);
localTime.minusNanos(1);
//一小时后,一分钟后
localTime.plusHours(1);
localTime.plusMinutes(1);
localTime.plusSeconds(1);
localTime.plusNanos(1);
LocalDate myDate = LocalDate.of(2018, 9, 3);
LocalDate nowDate = LocalDate.now();
//判断都是boolean型
nowDate.equals(myDate);
myDate.isBefore(nowDate);
myDate.isAfter(nowDate);
//判断生日
LocalDate myDate2 = LocalDate.of(1999, 2, 23);
LocalDate nowDate2 = LocalDate.now();
MonthDay my = MonthDay.of(myDate2.getMonthValue(), myDate2.getDayOfMonth());
MonthDay now = MonthDay.from(nowDate2);
// MonthDay now = MonthDay.of(nowDate2.getMonthValue(), nowDate2.getDayOfMonth());
if (my.equals(now)) {
System.out.println("生日快乐!");
}
}
}
2.Instant 时间戳
Instant类由一个静态工厂方法now()返回当前时间戳;
与Date类似,可以互相转换;
/**
* Instant时间戳
*/
public class Demo05Instant {
public static void main(String[] args) {
//世界时间 时间戳
Instant instant = Instant.now();
//2022-07-22T15:24:11.584Z
System.out.println(instant);
//转为系统默认时间,
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
//2022-07-22T23:24:11.584+08:00[Asia/Shanghai]
System.out.println(zonedDateTime);
//基本的增删
//Instant and Date 互相转换
Date date= Date.from(instant);
//Fri Jul 22 23:24:11 CST 2022
System.out.println(date);
Instant instant1 = date.toInstant();
//2022-07-22T15:24:11.584Z
System.out.println(instant1);
}
}
3.DateTimeFormatter:时间格式化和解析
-
全新的日期与时间格式器;
-
正反都能调用format方法;
/**
* DateTimeFormat
*/
public class Demo06DateTimeFormat {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
//解析,格式化器
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEE a");
//正向格式化
String now1 = dtf.format(now);
//2022-07-22 23:35:21 星期五 下午
System.out.println(now1);
//逆向格式化
String now2 = now.format(dtf);
//2022-07-22 23:35:21 星期五 下午
System.out.println(now2);
//解析字符串时间
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateStr = "2022-07-22 23:34:55";
LocalDateTime ldt1 = LocalDateTime.parse(dateStr, dtf1);
//2022-07-22T23:34:55
System.out.println(ldt1);
}
}
4.Duration:计算时间间隔 Period:计算日期间隔
/**
* Period
*/
public class Demo07Period {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
//出生日期
LocalDate birthDate = LocalDate.of(1999, 02, 23);
//比较,计算现在年龄(today-birthDate)
Period between = Period.between(birthDate, today);
//现在年龄:23岁4个月29天
System.out.println("现在年龄:"+between.getYears()+"岁"+between.getMonths()+"个月"+between.getDays()+"天");
}
}
/**
* Duration
*/
public class Demo08Duration {
public static void main(String[] args) {
LocalDateTime today = LocalDateTime.now();
LocalDateTime birthDate = LocalDateTime.of(1999, 2, 23, 10, 48, 06, 06);
Duration duration = Duration.between(today, birthDate);
//两个时间差的精确值,每个都单独使用
duration.toDays();//差天数
duration.toHours();
duration.toMinutes();
duration.toMillis();//毫秒
duration.toNanos();
}
}
5.ChronoUnit类
用于在单个时间单位内测量一段时间,可以用于比较所有时间;
/**
* ChronoUnit
*/
public class Demo09ChronoUnit {
public static void main(String[] args) {
LocalDateTime today = LocalDateTime.now();
LocalDateTime birthDate = LocalDateTime.of(1999, 2, 23, 10, 48, 06, 06);
ChronoUnit.YEARS.between(birthDate,today);
ChronoUnit.MONTHS.between(birthDate,today);
ChronoUnit.WEEKS.between(birthDate,today);
ChronoUnit.DAYS.between(birthDate,today);
ChronoUnit.HOURS.between(birthDate,today);
ChronoUnit.MINUTES.between(birthDate,today);
ChronoUnit.SECONDS.between(birthDate,today);
ChronoUnit.MILLIS.between(birthDate,today);//毫秒
ChronoUnit.MICROS.between(birthDate,today);//微秒
ChronoUnit.NANOS.between(birthDate,today);
ChronoUnit.HALF_DAYS.between(birthDate,today);//相差半天数
ChronoUnit.DECADES.between(birthDate,today);//相差十年数
ChronoUnit.CENTURIES.between(birthDate,today);//相差世纪数
}
}