1 import java.sql.Timestamp;
2 import java.time.format.DateTimeFormatter;
3 import java.util.Calendar;
4 import java.util.Date;
5
6 /**
7 * 时间公共类
8 */
9 public class TimeUtil {
10
11 /**
12 * 格式化时间格式,如果时间戳为空,获取当前系统时间的时间戳
13 * @param time 要格式化的时间戳
14 * @param format 格式化格式
15 * @return formatTime 格式化时间
16 */
17 public static String getFormatTime(Timestamp time,String format){
18 // 创建统计时间
19 Timestamp calTime = null;
20 // 判断如果为空,获取当前系统时间
21 if(time == null){
22 calTime = new Timestamp(System.currentTimeMillis());
23 }else{
24 calTime = time;
25 }
26 // 格式化时间
27 DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
28 String formatTime = calTime.toLocalDateTime().format(dtf);
29 // 返回格式化时间
30 return formatTime;
31 }
32
33 /**
34 * 获取月初时间
35 * @param time 传入时间戳
36 * @return returnTime 月初时间戳
37 */
38 public static Timestamp getMonthStart(Timestamp time){
39 Date date = time;
40 Calendar calendar = Calendar.getInstance();
41 calendar.setTime(date);
42 int index = calendar.get(Calendar.DAY_OF_MONTH);
43 calendar.add(Calendar.DATE, (1 - index));
44 Date monthStart = calendar.getTime();
45 Timestamp returnTime = new Timestamp(monthStart.getTime());
46 return returnTime;
47 }
48
49 /**
50 * 获取月末时间
51 * @param time 传入时间戳
52 * @return returnTime 月末时间戳
53 */
54 public static Timestamp getMonthEnd(Timestamp time){
55 Date date = time;
56 Calendar calendar = Calendar.getInstance();
57 calendar.setTime(date);
58 calendar.add(Calendar.MONTH, 1);
59 int index = calendar.get(Calendar.DAY_OF_MONTH);
60 calendar.add(Calendar.DATE, (-index));
61 Date monthEnd = calendar.getTime();
62 Timestamp returnTime = new Timestamp(monthEnd.getTime());
63 return returnTime;
64 }
65
66 /**
67 * 获取当前时间的前一天
68 * @param time 传入一个时间戳
69 * @return returnDate 格式化后的时间
70 */
71 public static String getBeforeDay(Timestamp time){
72 Date date = time;
73 Calendar calendar = Calendar.getInstance();
74 calendar.setTime(date);
75 calendar.add(Calendar.DAY_OF_MONTH, -1);
76 date = calendar.getTime();
77 String returnDate = TimeUtil.getFormatTime(new Timestamp(date.getTime()) , "yyyy-MM-dd");
78 return returnDate;
79 }
80 }