Date 类常见用法
- 获取当前时间(Date中存放的是时间戳)
/* 获取当前日期直接输出 */
Date today = new Date();
System.out.println(today);
/* 输出:Fri Oct 01 14:31:04 CST 2021*/
- 获取Date的部分信息(年、月、日)
Date date = new Date();
int dateDay = date.getDay(); /* 获取星期数 */
int dateYear = date.getYear();
int dateMonth = date.getMonth();
int dateDate = date.getDate();
int dateHour = date.getHours();
int dateMinute = date.getMinutes();
int dateSecond = date.getSeconds();
System.out.print(dateDay+" "+dateYear+"/"+dateMonth+"/"+dateDate);
System.out.println(" "+ dateHour+"/"+dateMinute+"/"+dateSecond);
Date 和 String 的相互转换
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
/* 将Date转换成String sdf.format */
Date date = new Date();
String today = sdf.format(date);
System.out.println(today);
/* 输出:2021年10月01日 21时00分45秒 */
/* 将String转换成Date sdf.parse */
/* 在把一个字符串解析为日期的时候,注意格式必须和给定的字符串格式匹配 */
String dateInString = today;
Date newDate = null;
try {
newDate = sdf.parse(dateInString);
} catch (ParseException e) {
}
System.out.println(newDate);
/* 输出:Fri Oct 01 14:31:04 CST 2021 */
LocalDate
从Java 8之后,Java里面添加了许多的新特性,其中一个最常见也是最实用的便是日期处理的类——LocalDate。
新增的日期jar主要有三种:
java.time.LocalDate -> 只对年月日做出处理
java.time.LocalTime -> 只对时分秒纳秒做出处理
java.time.LocalDateTime -> 同时可以处理年月日和时分秒
LocalDate today = LocalDate.now();
System.out.println(today);
int year = localDate.getYear();
int month = localDate.getMonthValue(); //6
Month month2 = localDate.getMonth(); //"JUNE"
int dayofMonth = today.getDayOfMonth();
DayOfWeek dayofWeek = today.getDayOfWeek();
/* 获取当前时区的日期 */
LocalDate localDate = LocalDate.now();
System.out.println("localDate: " + localDate);
/* 获取当前时区的时间 */
LocalTime localTime = LocalTime.now();
System.out.println("localTime: " + localTime);
/* 获取当前时区的日期时间 */
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("localDateTime: " + localDateTime);
/* 格式化时间 */
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
System.out.println("格式化之后的时间: " + localDateTime.format(formatter));