1.LocalDateTime转为yyyy-MM-dd HH:mm:ss
LocalDateTime time1 = LocalDateTime.now()
String = time1.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
2.LocalDateTime时间大小比较
// 自定义开始时间
LocalDateTime startTime = LocalDateTime.of(2021, 10, 22, 10, 10, 10)
// 自定义结束时间
LocalDateTime endTime = LocalDateTime.of(2021, 10, 22, 11, 11, 11)
//比较 开始时间在结束时间之后,这里返回false
System.out.println(startTime.isAfter(endTime))
//比较 开始时间在结束时间之前,这里返回true
System.out.println(startTime.isBefore(endTime))
3.Date日期增加一天
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
Date startDate = sdf.parse(2020-11-11)
Date endDate = null
try {
Calendar c = Calendar.getInstance()
c.setTime(startDate)
c.add(Calendar.DATE, 1)
endDate = c.getTime()
}catch (Exception e){
log.error("转换日期格式出错",e)
}
System.out.println(sdf.format(startDate))
System.out.println(sdf.format(endDate))
4.LocalDateTime日期增、减
LocalDateTime time = LocalDateTime.now()
time = time.plusMinutes(5)
time = time.minusMinutes(5)
time = time.plusHours(5)
time = time.minusHours(5)
5.yyyyMM(yyyyMMdd)格式转为yyyy-MM(yyyy-MM-dd)格式
// yyyyMM格式转为yyyy-MM格式
String date = "201402"
Date parse = null
String dateString = ""
try {
parse = new SimpleDateFormat("yyyyMM").parse(date)
dateString = new SimpleDateFormat("yyyy-MM").format(parse)
} catch (Exception e) {
dateString=null
log.error("日期格式转换出错,{}",date)
}
System.out.println(dateString)
// yyyyMMdd格式转为yyyy-MM-dd格式
String date = "20140204"
Date parse = null
String dateString = ""
try {
parse = new SimpleDateFormat("yyyyMMdd").parse(date)
dateString = new SimpleDateFormat("yyyy-MM-dd").format(parse)
} catch (Exception e) {
dateString=null
log.error("日期格式转换出错,{}",date)
}
System.out.println(dateString)
6、获取yyyyMMddHHmmss格式时间,并获取毫秒和6位UUID
String strLocalDateTime = LocalDateTime.now().toString()
// 或者 String strLocalDateTime = String.valueOf(System.currentTimeMillis())
System.out.println("日期格式:"+strLocalDateTime)
String strDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
System.out.println("yyyyMMddHHmmss格式:"+strDate)
strDate += strLocalDateTime.substring(strLocalDateTime.length()-3)
System.out.println("加上毫秒:"+strDate)
strDate += UUIDUtil.getUUID().substring(0,6)
System.out.println("加上UUID:"+strDate)
输出:
日期格式:2022-04-29T15:34:19.329
yyyyMMddHHmmss格式:20220429153419
加上毫秒:20220429153419329
加上UUID:202204291534193295c36da