DateFormatUtil.java
3.18 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package com.subsidy.util;
import java.awt.SystemTray;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
/**
* 处理时间工具
*
* @author DengMin
* @date 2019/08/27 13:56
**/
public class DateFormatUtil {
public final static String YEAR = "yyyy";
public final static String FMT_sdf14_L = "yyyy-MM-dd HH:mm:ss";
public final static String FMT_sdf_yMd = "yyyy-MM-dd";
public final static String FMT_sdf_yM = "yyyy-M";
public final static String FMT_sdf_yMM = "yyyy-MM";
public final static String FMT_sdf_Hm = "H:mm";
public final static String FMT_sdf_HHmm = "HH:mm";
public final static String cron = "s m H d M ? yyyy";
/**
* Date转String,自定义格式
* @param date
* @param pattern
* @return
*/
public static String format(Date date, String pattern) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* LocalDateTime转String,自定义格式
* @param localDateTime
* @param pattern
* @return
*/
public static String format(LocalDateTime localDateTime, String pattern) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(localDateTime);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* String转Date,自定义格式
* @param date
* @param pattern
* @return
*/
public static Date parse(String date, String pattern) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(date);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 比较两个时间
* .after 大于
* .before 小于
* @param d1
* @param d2
* @return
*/
public static boolean compare(Date d1, Date d2 ) {
return !d1.after(d2);
}
/**
* Data转Cron
* @param date
* @return
*/
public static String getCron(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("s m H d M ? yyyy");
return sdf.format(date);
}
public static Date localDateTimeToDate(LocalDateTime dateTime) {
if(dateTime == null) {
return null;
}
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = dateTime.atZone(zoneId);
return Date.from(zdt.toInstant());
}
public static LocalDateTime secondToLocalDateTime(Long second) {
if(second != null) {
return LocalDateTime.ofEpochSecond(second, 0, ZoneOffset.ofHours(8));
}
return LocalDateTime.now();
}
public static Long LocalDateTimeToSecond(LocalDateTime localDateTime) {
if(localDateTime != null) {
return localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
}
return System.currentTimeMillis();
}
}