5.1 格式化时间 SimpleDateFormat、printf
public class Main{public static void main(String[] args){Date date = new Date();String strDateFormat = "yyyy-MM-dd HH:mm:ss";SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);System.out.println(sdf.format(date)); // 2015-03-27 21:13:23//c的使用System.out.printf("全部日期和时间信息:%tc%n",date); // 星期一 九月 10 10:43:36 CST 2012}}
5.2 获取某个时间点 Calendar
public class Main {public static void main(String[] args) {Calendar cal = Calendar.getInstance();int day = cal.get(Calendar.DATE);int month = cal.get(Calendar.MONTH) + 1;int year = cal.get(Calendar.YEAR);int dow = cal.get(Calendar.DAY_OF_WEEK);int dom = cal.get(Calendar.DAY_OF_MONTH);int doy = cal.get(Calendar.DAY_OF_YEAR);System.out.println("当期时间: " + cal.getTime()); // Fri Mar 27 21:44:15 CST 2015System.out.println("日期: " + day); // 27System.out.println("月份: " + month); // 3System.out.println("年份: " + year); // 2015System.out.println("一周的第几天: " + dow); // 6, 星期日为一周的第一天输出为 1,星期一输出为 2,以此类推System.out.println("一月中的第几天: " + dom); // 27System.out.println("一年的第几天: " + doy); // 86}}
5.3 时间戳转换成时间
public class Main{public static void main(String[] args){Long timeStamp = System.currentTimeMillis(); //获取当前时间戳SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp)))); // 时间戳转换成时间System.out.println("格式化结果:" + sd); // 2021-12-21 10:35:35}}
5.4 LocalDateTime
JDK 8 用 LocalDateTime 来代替 Calendar
public static void main(String[] args) {LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDateTime); // 2021-12-22T08:56:53.923System.out.println(localDateTime.getYear()); // 2021System.out.println(localDateTime.getHour()); // 8}
5.5 Instant
JDK 8 用 Instant 来代替 Date,时区需要加 8 小时
public static void main(String[] args) {Instant instant = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));System.out.println(instant); // 2021-12-22T08:59:57.491Z}
5.6 DateTimeFormatter
JDK 8 使用 DateTimeFormatter 来代替 SimopleDateFormat,时间使用 LocalDateTime
public static void main(String[] args) {DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String format = dtf.format(LocalDateTime.now());System.out.println(format); // 2021-12-22 09:04:47}
5.7 日期比较
- 使用 getTime() 方法获取两个日期(自1970年1月1日经历的毫秒数值),然后比较这两个值。
- 使用方法 before(),after() 和 equals()。例如,一个月的12号比18号早,则 new Date(99, 2, 12).before(new Date (99, 2, 18)) 返回true。
- 使用 compareTo() 方法,它是由 Comparable 接口定义的,Date 类实现了这个接口。

