吴小龙同學

时间工具类TimeUtil

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
public class TimeUtil {
/**
* 获取当前时间
*
* @param format "yyyy-MM-dd HH:mm:ss"
*/
public static String getCurrentTime(String format) {
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.getDefault());
return simpleDateFormat.format(date);
}
/**
* 获取当前时间为本月的第几周
*/
public static int getWeekOfMonth() {
Calendar calendar = Calendar.getInstance();
int week = calendar.get(Calendar.WEEK_OF_MONTH);
return week - 1;
}
/**
* 获取当前时间为本周的第几天
*/
public static int getDayOfWeek() {
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (day == 1) {
day = 7;
} else {
day = day - 1;
}
return day;
}
/**
* 获取当前时间的年份
*/
public static int getYear() {
Calendar calendar = GregorianCalendar.getInstance();
return calendar.get(Calendar.YEAR);
}
/**
* 获取当前时间的月份
*/
public static int getMonth() {
Calendar calendar = GregorianCalendar.getInstance();
return calendar.get(Calendar.MONTH);
}
/**
* 获取当前时间是哪天
*/
public static int getDay() {
Calendar calendar = GregorianCalendar.getInstance();
return calendar.get(Calendar.DATE);
}
/**
* @param date1
* @param date2
* @return 1:date1大于date2;
* -1:date1小于date2
*/
public static int compareDate(String date1, String date2, String format) {
DateFormat df = new SimpleDateFormat(format, Locale.getDefault());
try {
Date dt1 = df.parse(date1);
Date dt2 = df.parse(date2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
/**
* 时间加减
*
* @param day 如"2015-09-22"
* @param dayAddNum 加减值
* @return
*/
public static String timeAddSubtract(String day, int dayAddNum) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
try {
Date newDate = new Date(simpleDateFormat.parse(day).getTime() + dayAddNum * 24 * 60 * 60 * 1000);
return simpleDateFormat.format(newDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 毫秒格式化
*
* @param millisecond 如"1449455517602"
* @param format 如"yyyy-MM-dd HH:mm:ss"
* @return
*/
public static String millisecond2String(long millisecond, String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.getDefault());
return simpleDateFormat.format(millisecond);
}
}


联系我

我的微信公众号:吴小龙同学,欢迎关注交流~

赞助商:躲角落的猫咪