时间日期处理

Posted by 石玉军 on 2018-07-26
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
public class DateUtil {

private static Logger logger = Logger.getLogger(DateUtil.class);
private static String defaultDatePattern = null;
private static String timePattern = "HH:mm";
private static Calendar cale = Calendar.getInstance();
public static final String TS_FORMAT = DateUtil.getDatePattern() + " HH:mm:ss.S";
/**
* 日期格式yyyy-MM字符串常量
*/
private static final String MONTH_FORMAT = "yyyy-MM";
/**
* 日期格式yyyy-MM-dd字符串常量
*/
private static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* 日期格式HH:mm:ss字符串常量
*/
private static final String HOUR_FORMAT = "HH:mm:ss";
/**
* 日期格式yyyy-MM-dd HH:mm:ss字符串常量
*/
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 某天开始时分秒字符串常量 00:00:00
*/
private static final String DAY_BEGIN_STRING_HHMMSS = " 00:00:00";
/**
* 某天结束时分秒字符串常量 23:59:59
*/
public static final String DAY_END_STRING_HHMMSS = " 23:59:59";
private static SimpleDateFormat sdf_date_format = new SimpleDateFormat(DATE_FORMAT);
private static SimpleDateFormat sdf_hour_format = new SimpleDateFormat(HOUR_FORMAT);
public static SimpleDateFormat sdf_datetime_format = new SimpleDateFormat(DATETIME_FORMAT);



public DateUtil() {
}

/**
* 获得服务器当前日期及时间,以格式为:yyyy-MM-dd HH:mm:ss的日期字符串形式返回
*/
public static String getDateTime() {
try {
return sdf_datetime_format.format(cale.getTime());
} catch (Exception e) {
logger.debug("DateUtil.getDateTime():" + e.getMessage());
return "";
}
}

/**
* 获得服务器当前日期,以格式为:yyyy-MM-dd的日期字符串形式返回
*/
public static String getDate() {
try {
return sdf_date_format.format(cale.getTime());
} catch (Exception e) {
logger.debug("DateUtil.getDate():" + e.getMessage());
return "";
}
}

/**
* 获得服务器当前时间,以格式为:HH:mm:ss的日期字符串形式返回
*/
public static String getTime() {
String temp = " ";
try {
temp += sdf_hour_format.format(cale.getTime());
return temp;
} catch (Exception e) {
logger.debug("DateUtil.getTime():" + e.getMessage());
return "";
}
}

/**
* 获得服务器当前日期的年份
*/
public static String getYear() {
try {
return String.valueOf(cale.get(Calendar.YEAR));
} catch (Exception e) {
logger.debug("DateUtil.getYear():" + e.getMessage());
return "";
}
}

/**
* 获得服务器当前日期的月份
*/
public static String getMonth() {
try {
java.text.DecimalFormat df = new java.text.DecimalFormat();
df.applyPattern("00;00");
return df.format((cale.get(Calendar.MONTH) + 1));
} catch (Exception e) {
logger.debug("DateUtil.getMonth():" + e.getMessage());
return "";
}
}

/**
* 获得服务器在当前月中天数
*/
public static String getDay() {
try {
return String.valueOf(cale.get(Calendar.DAY_OF_MONTH));
} catch (Exception e) {
logger.debug("DateUtil.getDay():" + e.getMessage());
return "";
}
}


/**
* 比较两个日期相差的天数
*/
public static double getDoubleMargin(String date1, String date2) {
double margin;
try {
ParsePosition pos = new ParsePosition(0);
ParsePosition pos1 = new ParsePosition(0);
Date dt1 = sdf_datetime_format.parse(date1, pos);
Date dt2 = sdf_datetime_format.parse(date2, pos1);
long l = dt1.getTime() - dt2.getTime();
margin = (l / (24 * 60 * 60 * 1000.00));
return margin;
} catch (Exception e) {
logger.debug("DateUtil.getMargin():" + e.toString());
return 0;
}
}

/**
* 比较两个日期相差的月数
*/
public static int getMonthMargin(String date1, String date2) {
int margin;
try {
margin = (Integer.parseInt(date2.substring(0, 4)) - Integer.parseInt(date1.substring(0, 4))) * 12;
margin += (Integer.parseInt(date2.substring(4, 7).replaceAll("-0",
"-")) - Integer.parseInt(date1.substring(4, 7).replaceAll("-0", "-")));
return margin;
} catch (Exception e) {
logger.debug("DateUtil.getMargin():" + e.toString());
return 0;
}
}

/**
* 返回日期加X天后的日期
*/
public static String addDay(String date, int i) {
try {
GregorianCalendar gCal = new GregorianCalendar(
Integer.parseInt(date.substring(0, 4)),
Integer.parseInt(date.substring(5, 7)) - 1,
Integer.parseInt(date.substring(8, 10)));
gCal.add(GregorianCalendar.DATE, i);
return sdf_date_format.format(gCal.getTime());
} catch (Exception e) {
logger.debug("DateUtil.addDay():" + e.toString());
return getDate();
}
}

/**
* 返回日期加X月后的日期
*/
public static String addMonth(String date, int i) {
try {
GregorianCalendar gCal = new GregorianCalendar(
Integer.parseInt(date.substring(0, 4)),
Integer.parseInt(date.substring(5, 7)) - 1,
Integer.parseInt(date.substring(8, 10)));
gCal.add(GregorianCalendar.MONTH, i);
return sdf_date_format.format(gCal.getTime());
} catch (Exception e) {
logger.debug("DateUtil.addMonth():" + e.toString());
return getDate();
}
}

/**
* 返回日期加X年后的日期
*/
public static String addYear(String date, int i) {
try {
GregorianCalendar gCal = new GregorianCalendar(
Integer.parseInt(date.substring(0, 4)),
Integer.parseInt(date.substring(5, 7)) - 1,
Integer.parseInt(date.substring(8, 10)));
gCal.add(GregorianCalendar.YEAR, i);
return sdf_date_format.format(gCal.getTime());
} catch (Exception e) {
logger.debug("DateUtil.addYear():" + e.toString());
return "";
}
}

/**
* 返回某年某月中的最大天
*/
public static int getMaxDay(int iyear, int imonth) {
int day = 0;
try {
if (imonth == 1 || imonth == 3 || imonth == 5 || imonth == 7
|| imonth == 8 || imonth == 10 || imonth == 12) {
day = 31;
} else if (imonth == 4 || imonth == 6 || imonth == 9 || imonth == 11) {
day = 30;
} else if ((0 == (iyear % 4)) && (0 != (iyear % 100)) || (0 == (iyear % 400))) {
day = 29;
} else {
day = 28;
}
return day;
} catch (Exception e) {
logger.debug("DateUtil.getMonthDay():" + e.toString());
return 1;
}
}



/**
* 取得当前时间的Calendar日历对象
*/
public Calendar getToday() throws ParseException {
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
String todayAsString = df.format(today);
Calendar cal = new GregorianCalendar();
cal.setTime(convertStringToDate(todayAsString));
return cal;
}

/**
* 将日期类转换成指定格式的字符串形式
*/
public static final String getDateTime(String aMask, Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate == null) {
logger.error("aDate is null!");
} else {
df = new SimpleDateFormat(aMask);
returnValue = df.format(aDate);
}
return (returnValue);
}

/**
* 将指定的日期转换成默认格式的字符串形式
*/
public static final String convertDateToString(Date aDate) {
return getDateTime(getDatePattern(), aDate);
}

/**
* 将日期字符串按指定格式转换成日期类型
*/
public static final Date convertStringToDate(String aMask, String strDate)
throws ParseException {
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(aMask);

if (logger.isDebugEnabled()) {
logger.debug("converting '" + strDate + "' to date with mask '" + aMask + "'");
}
try {
date = df.parse(strDate);
} catch (ParseException pe) {
logger.error("ParseException: " + pe);
throw pe;
}
return (date);
}


/**
* 返回一个JAVA简单类型的日期字符串
*/
public static String getSimpleDateFormat() {
SimpleDateFormat formatter = new SimpleDateFormat();
String NDateTime = formatter.format(new Date());
return NDateTime;
}

/**
* 将指定字符串格式的日期与当前时间比较
*/
public static int compareToCurTime(String strDate) {
if (StringUtils.isBlank(strDate)) {
return -1;
}
Date curTime = cale.getTime();
String strCurTime = null;
try {
strCurTime = sdf_datetime_format.format(curTime);
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("[Could not format '" + strDate + "' to a date, throwing exception:" + e.getLocalizedMessage() + "]");
}
}
if (StringUtils.isNotBlank(strCurTime)) {
return strCurTime.compareTo(strDate);
}
return -1;
}

/**
* 返回指定年份中指定月份的天数
*/
public static String getMonthLastDay(int year, int month) {
int[][] day = {{0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return day[1][month] + "";
} else {
return day[0][month] + "";
}
}

/**
* 判断是平年还是闰年
*/
public static boolean isLeapyear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400) == 0) {
return true;
} else {
return false;
}
}

/**
* 取得当前时间的日戳
*/
@SuppressWarnings("deprecation")
public static String getTimestamp() {
Date date = cale.getTime();
String timestamp = "" + (date.getYear() + 1900) + date.getMonth()
+ date.getDate() + date.getMinutes() + date.getSeconds()
+ date.getTime();
return timestamp;
}

/**
* 取得指定时间的日戳
*/
@SuppressWarnings("deprecation")
public static String getTimestamp(Date date) {
String timestamp = "" + (date.getYear() + 1900) + date.getMonth()
+ date.getDate() + date.getMinutes() + date.getSeconds()
+ date.getTime();
return timestamp;
}
/**
* 将日期字符串按默认格式转换成日期类型
*/
public static Date convertStringToDate(String strDate)
throws ParseException {
Date aDate = null;

try {
if (logger.isDebugEnabled()) {
logger.debug("converting date with pattern: " + getDatePattern());
}
aDate = convertStringToDate(getDatePattern(), strDate);
} catch (ParseException pe) {
logger.error("Could not convert '" + strDate + "' to a date, throwing exception");
throw new ParseException(pe.getMessage(), pe.getErrorOffset());
}
return aDate;
}
/**
* 返回默认的日期格式
*/
public static synchronized String getDatePattern() {
defaultDatePattern = "yyyy-MM-dd";
return defaultDatePattern;
}

}