public static void main(String[] args) throws ParseException {
Date date = new Date();
//Tue Jun 07 10:01:54 CST 2022
System.out.println(date);
long time = date.getTime();
//1654567314290
System.out.println(time);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//2022-06-07 10:01:54
System.out.println(simpleDateFormat.format(date));
String time1 = "2022-06-7";
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date parsetime = simpleDateFormat1.parse(time1);
//Tue Jun 07 00:00:00 CST 2022
System.out.println(parsetime);
//1654531200000
System.out.println(parsetime.getTime());
//时间转换 JDK8以上
LocalDateTime now = LocalDateTime.now();//获取当前时间
System.out.println(now);//2022-06-07T11:03:52.833935700
String formatnow = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(formatnow);//2022-06-07 14:52:35
//自定义时间
LocalDateTime of = LocalDateTime.of(2022, 6, 7, 1, 1, 1);
System.out.println(of);//2022-06-07T00:00 注意这里带T
System.out.println(of.getYear());//2022
System.out.println(of.getMonthValue());//6
System.out.println(of.getDayOfMonth());//7
System.out.println(of.getHour());//1
System.out.println(of.getMinute());//1
System.out.println(of.getSecond());//1
System.out.println(of.getDayOfWeek());//TUESDAY
System.out.println(of.toLocalDate());//2022-6-7
System.out.println(of.toLocalTime());//01:01:01
//format方法把LocalDateTime对象转换成指定字符串
String time2 = of.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"));
System.out.println(time2);//2022年06月07日 01时01分01秒
//parse 使用特定的日期本字符串转化为 LocalDateTime的对象实例。
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
LocalDateTime parse = LocalDateTime.parse("2022年06月07日 01时01分01秒", dateTimeFormatter);//LocalDateTime对象
System.out.println(parse);//2022-06-07T01:01:01
LocalDateTime of1 = LocalDateTime.of(2022, 8, 9, 12, 6);
//plusYear LocalDateTime对象年份增加减少方法。
System.out.println(of1);//2022-08-09T12:06 原本时间
LocalDateTime newof1 = of1.plusYears(1);
System.out.println(newof1);//2023-08-09T12:06 +1的时间
//withYear LocalDateTime对象年份修改方法。
System.out.println(of1.withYear(2040));//2040-08-09T12:06 直接修改成2040年
//Period 返回2个LocalDate对象的间隔时间 只返回年月日
LocalDate of2 = LocalDate.of(2022, 1, 1);
LocalDate of3 = LocalDate.of(2023, 8, 20);
Period between = Period.between(of2, of3);
System.out.println(between);//P1Y8M20D
System.out.println(between.getYears());//1
System.out.println(between.getMonths());//8 获取月分
System.out.println(between.getDays());//20 获取天数
//Duration 返回2个LocalTime对象的间隔时间 只返回时分秒
LocalTime of4 = LocalTime.of(12, 0, 0);
LocalTime of5 = LocalTime.of(14, 8, 20);
Duration between1 = Duration.between(of4, of5);
System.out.println(between1);//PT2H8M20S
System.out.println(between1.toSeconds());//7700 toSeconds获取多少秒
System.out.println(between1.toHours());//2 toHours获取小时
}
Java时间格式转换
于 2022-06-07 12:31:46 首次发布