Java常用时间类

时间戳相关操作

// 创建 instant 对象
Instant instant = Instant.now();
// instant 获取当前秒数
long currentSecond = instant.getEpochSecond();
// instant 获取当前毫秒数
long currentMilli = instant.toEpochMilli();
// System 获取当前毫秒数
long currentTimeMillis = System.currentTimeMillis();

Date(如果JDK >= 1.8 不建议使用)

使用 Date 和 SimpleDateFormat会引发线程安全问题,当多个线程同时操作这个对象时就会出现线程安全问题
1.在使用SimpleDateFormat时候尽量不要共享,每次使用的时候都创建一个新的对象
2.使用ThreadLocal来包装一下formater对象
3.使用LocalDateTime这个类来进行日期转换和处理(推荐)

// 获取当前你时间
Date date = new Date();
// 格式化时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");

LocalDate

// 获取当前日期
LocalDate localDate = LocalDate.now();
// 自定义日期
LocalDate localDateOf = LocalDate.of(2022, 7, 8);
// 获取年
int year = localDate.getYear();
// 获取月
int month = localDate.getMonthValue();
// 获取日
int day = localDate.getDayOfMonth();
// 月初
LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
// 月末
LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
// 年初
LocalDate firstDayOfYear = localDate.with(TemporalAdjusters.firstDayOfYear());
// 年末
LocalDate lastDayOfYear = localDate.with(TemporalAdjusters.lastDayOfYear());

LocalTime

// 获取当前时间
LocalTime localTime = LocalTime.now();
// 自定义时间
LocalTime customizeLocalTime = LocalTime.of(13, 51, 10);
//获取小时
int hour = localTime.getHour();
int hour1 = localTime.get(ChronoField.HOUR_OF_DAY);
//获取分
int minute = localTime.getMinute();
int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR);
//获取秒
int second = localTime.getSecond();
int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);

LocalDateTime

注意LocalDateTime 是没有时区概念的,如果服务器是utc时间 返回做本地化的时候需要注意一下

// 获取当前时间
LocalDateTime localDateTime = LocalDateTime.now();
// 自定义当前时间
LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56);
// 格式化当前时间
String localDateTimeFormat = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 当前时间加 1年
LocalDateTime localDateTimePlusYears = localDateTime.plusYears(1);
// 当前时间减 1年
LocalDateTime localDateTimeMinusYears = localDateTime.minusYears(1);
// 当前时间加 1个月
LocalDateTime localDateTimePlusMonths = localDateTime.plusMonths(1);
// 当前时间减 1个月
LocalDateTime localDateTimeMinusMonths = localDateTime.minusMonths(1);
// 当前时间减 1天
LocalDateTime localDateTimePlusDays = localDateTime.plusDays(1);
// 当前时间减 1天
LocalDateTime localDateTimeMinusDays = localDateTime.minusDays(1);
// 获取日期
LocalDate localDate = localDateTime.toLocalDate();
// 获取时间
LocalTime localTime = localDateTime.toLocalTime();

Spring Boot 应用

实体类字段加上@JsonFormat:返给前端格式化

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private LocalDateTime gmtModified;

实体类字段加上@DateTimeFormat:接收前端格式化

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime gmtModified;

posted on 2022-07-13 09:30  青华佳园  阅读(155)  评论(0)    收藏  举报

导航