DateUtil.java
3.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package cn.living.sharecenter.utils;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static String getDateStringByFormat(Date date, String format) throws Exception{
if(StringUtil.isEmpty(format)){
throw new Exception("时间格式不能为空");
}
if(null == date){
throw new Exception("时间不能为空");
}
SimpleDateFormat simple = new SimpleDateFormat(format);
return simple.format(date);
}
/**
* 获取指定格式时间(LocalDateTime)
*
* @param dateTime LocalDateTime
* @param format 时间格式
* @return 指定格式时间字符串
*/
public static String getDateStringByFormat(LocalDateTime dateTime, String format) throws Exception {
if(StringUtil.isEmpty(format)){
throw new Exception("时间格式不能为空");
}
if(null == dateTime){
throw new Exception("时间不能为空");
}
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return df.format(dateTime);
}
public static Date getDateByFormat(String time, String format) throws Exception{
if(StringUtil.isEmpty(format)){
throw new Exception("时间格式不能为空");
}
if(StringUtil.isEmpty(time)){
throw new Exception("时间不能为空");
}
SimpleDateFormat simple = new SimpleDateFormat(format);
return simple.parse(time);
}
public static int getMinuteByNow(Date time) throws Exception{
Date date = new Date();
long millsecond = date.getTime()-time.getTime();
if(millsecond < 0){
throw new Exception("时间超前异常");
}
int minute = (int) millsecond / 60000;
return minute;
}
/**
* 获取系统时间后一个月的第一天
*/
public static String getFirstDayAfterMonth() throws Exception{
Calendar c = Calendar.getInstance();
String time = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH)+2)%13 + "-1";
return time;
}
/**
* 获取系统时间每月最后一天23:59:59到当前时间的毫秒值
* @throws Exception
*/
public static long getMillSecondTheMonthUtilNow() throws Exception{
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Calendar nowCalendar = Calendar.getInstance();
return calendar.getTime().getTime() - nowCalendar.getTime().getTime();
}
/**
* @Description: 增加天数
* @param :date
* 要进行添加的日期
* @param :days
* 要增加的天数
* @return 增加天数后的日期
* @throws Exception
*/
public static Date addDay(Date date, int days) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.DATE, days);
return cd.getTime();
}
}