-
Notifications
You must be signed in to change notification settings - Fork 2
/
DateTools.java
executable file
·1655 lines (1503 loc) · 54.4 KB
/
DateTools.java
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import org.apache.log4j.Logger;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateTools {
private static final Logger logger = Logger.getLogger(DateTools.class);
/**
* Chinese date time formate
*/
public static final String CHINESE_DATE_TIME = "yyyy年MM月dd日 HH:mm";
/**
* Chinese date format
*/
public static final String CHINESE_DATE = "yyyy年MM月dd日";
/**
* 月日
*/
public static final String CHINESE_MONTH_DATE = "MM月dd日";
/**
* 月日 时分
*/
public static final String CHINESE_MONTH_TIME = "MM月dd日 HH:mm";
/**
* Default date time format
*/
public static final String DEFAULT_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
/**
* Default date time format
*/
public static final String DEFAULT_DATE_TIME_SECOND = "yyyy-MM-dd HH:mm";
/**
* Default date time format
*/
public static final String DEFAULT_DATE_TIME_HOUR = "yyyy-MM-dd HH";
/**
* Default date format
*/
public static final String DEFAULT_DATE = "yyyy-MM-dd";
/**
* Default time format
*/
public static final String DEFAULT_TIME = "HH:mm:ss";
public static final String DEFAULT_TIME_HMS = "HHmmss";
/**
* For log and file's date format
*/
public static final String LOG_DATE_TIME = "yyyyMMddHHmmssSSS";
public static final String TIME_STAMP = "yyyyMMddHHmmssSSS";
public static final String TIME_STAMP_2 = "yyyyMMddHHmmss";
public static final String TRADE_TIME_STAMP = "yyyy-MM-dd HH:mm:ss,SSS";
public static final String YMD_TIME_STAMP = "yyyyMMdd";
/**
* For log and file's date format
*/
public static final String LOG_DATE_TIME2 = "yyMMddHHmmssSSS";
public static final String YMD_TIME_STAMP2 = "yyMMdd";
/**
* 一天的表示形式
*/
public static final long DURATION = 1000L * 60 * 60 * 24;//一天
public static final long DURATION_HOUR = 1000L * 60 * 60;//一小时
public static final String[] weeks = new String[]{"周日","周一", "周二", "周三", "周四", "周五", "周六"};
/**
* Count the days between 2 date,if the first date argument is before the
* second one, a negative number wiil be returned
*
* @param date1 A <code>java.util.Date</code> object
* @param date2 A <code>java.util.Date</code> object
* @return Day counts between the two input day
* If the first date argument is before the seconde one,
* a negative number will be returned.
*/
public static int daysBetween(Date date1, Date date2) {
if (date1 == null || date2 == null) return 0;
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(date1);
GregorianCalendar cal2 = new GregorianCalendar();
cal2.setTime(date2);
int before = cal1.compareTo(cal2);
//make the later one always in cal1
if (before < 0) {
cal1.setTime(date2);
cal2.setTime(date1);
}
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
int yearBetween = year1 - year2;
for (int i = 0; i < yearBetween; i++) {
cal2.set(Calendar.YEAR, year2 + i);
day1 = day1 + cal2.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return (day1 - day2) * before;
}
/**
* 计算两个日期的时间差 返回具体的天数
*
* @param compareTime
* @param currentTime
* @return int
*/
public static int hoursBetween(Date compareTime, Date currentTime) {
if (compareTime == null || currentTime == null)
return 0;
return (int) ((compareTime.getTime() - currentTime.getTime()) / DURATION);
}
/**
* 计算两个时间之间的小时数,精确到秒。
* <p>比如:2008-07-10 17:41:01 和 2008-07-11 17:41:01 之间相差为 24 个小时。</p>
* <p>比如:2008-07-10 17:41:01 和 2008-07-11 17:41:00 之间相差为 23 个小时。</p>
*
* @param time1 时间1
* @param time2 时间2
* @return int
*/
public static int calHours(Date time1, Date time2) {
if (time1 == null || time2 == null) {
return 0;
}
int v = (int) ((time1.getTime() - time2.getTime()) / DURATION_HOUR);
return Math.abs(v);
}
/**
* 计算两个时间之间相差的分钟数,“结束时间”减去“开始时间”之间的分钟数.
*
* @param beginTime 开始时间
* @param endTime 结束时间
* @return int 分钟数。如果开始时间或者结束时间为 null 的话,返回 0 。
*/
public static int minutesBetween(Date beginTime, Date endTime) {
if (beginTime == null || endTime == null) {
return 0;
}
long diff = endTime.getTime() - beginTime.getTime();
return (int) diff / (60 * 1000);
}
/**
* 计算两个日期的时间差 返回具体的天数
*
* @param compareTime
* @param currentTime
* @return int
*/
public static int secondsBetween(Date compareTime, Date currentTime) {
if (compareTime == null || currentTime == null)
return 0;
return (int) ((compareTime.getTime() - currentTime.getTime()) / 1000L);
}
/**
* 根据生日计算当前年龄.
* <p>准确到天,比如:<br/>
* 当前时间为 2008-06-17 ,生日为 1982-06-16 ,计算结果为 26<br/>
* 当前时间为 2008-06-17 ,生日为 1982-06-17 ,计算结果为 26<br/>
* 当前时间为 2008-06-17 ,生日为 1982-06-18 ,计算结果为 25<br/>
* </p>
*
* @param birthDay 必须是一个 Date 对象,否则直接返回 0
* @return
*/
public static int getAge(Object birthDay) {
Date aDate = null;
// if(birthDay instanceof DATE){
// DATE date = (DATE)birthDay;
// aDate = date.dateValue();
// }else if(birthDay instanceof Date){
if (birthDay instanceof Date) {
aDate = (Date) birthDay;
}
if (aDate != null) {
Calendar today = Calendar.getInstance();
Calendar birthday = Calendar.getInstance();
birthday.setTime(aDate);
int yearTotal = today.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
int bDay = today.get(Calendar.DAY_OF_YEAR) - birthday.get(Calendar.DAY_OF_YEAR);
//not yet match 1 round age, minus one year
if (bDay < 0) {
yearTotal = yearTotal - 1;
}
return yearTotal;
}
return 0;
}
/**
* Get birthday date according to the age
*
* @param age Age number
* @return The birthdate
*/
public static Date getBirthDay(int age) {
GregorianCalendar gc = new GregorianCalendar();
int currYear = gc.get(Calendar.YEAR);
gc.set(Calendar.YEAR, currYear - age);
Date birthDate = new Date(gc.getTime().getTime());//精确到天,haidong.zhou edit 2006-07-14
return birthDate;
}
/**
* Get recent date according to the days
*
* @param days day number
* @return The date
*/
public static Date getRecentDay(int days) {
GregorianCalendar gc = new GregorianCalendar();
int currDay = gc.get(Calendar.DAY_OF_YEAR);
gc.set(Calendar.DAY_OF_YEAR, currDay - days);
return new Date(gc.getTime().getTime());
}
// /**
// * Get Oracle's oracle.sql.DATE object by birthday(support for oracle)
// * @param age Age number
// * @return
// * @deprecated
// */
// public static DATE getOracleBirthDay(int age){
// DATE oracleDate = new DATE(new java.sql.Date(getBirthDay(age).getTime()));
// return oracleDate;
// }
/**
* Change a java.util.Date to a TO_DATE() format string for oracle sql format
*
* @param aDate A java.util.Date Object
* @return
*/
public static String toOracleDateFormat(Object aDate) {
StringBuffer buff = new StringBuffer();
buff.append("TO_DATE('");
if (aDate instanceof Date) {
String dateStr = parseToDefaultDateString((Date) aDate);
buff.append(dateStr).append("','YYYY-MM-DD HH24:MI:SS')");
//don't include other package
// }else if (aDate instanceof DATE){
// DATE date= (DATE) aDate;
// buff.append(date.stringValue()).append("','MM/DD/YYYY HH24:MI:SS')");
} else {
return null;
}
return buff.toString();
}
/**
* Change a java.util.Date to a TO_DATE() format string for oracle sql format
*
* @param aDate A java.util.Date Object
* @return
*/
public static String toOracleTimeFormat(Object aDate) {
StringBuffer buff = new StringBuffer();
buff.append("TO_DATE('");
if (aDate instanceof Date) {
String dateStr = parseToDefaultTimeString((Date) aDate);
buff.append(dateStr).append("','HH24:MI:SS')");
//don't include other package
// }else if (aDate instanceof DATE){
// DATE date= (DATE) aDate;
// buff.append(date.stringValue()).append("','MM/DD/YYYY HH24:MI:SS')");
} else {
return null;
}
return buff.toString();
}
/**
* Change a java.util.Date to a TO_DATE() format string for oracle sql format
*
* @param aDate A java.util.Date Object
* @return
*/
public static String toOracleDateTimeFormat(Object aDate) {
StringBuffer buff = new StringBuffer();
buff.append("TO_DATE('");
if (aDate instanceof Date) {
String dateStr = parseToDefaultDateTimeString((Date) aDate);
buff.append(dateStr).append("','YYYY-MM-DD HH24:MI:SS')");
//don't include other package
// }else if (aDate instanceof DATE){
// DATE date= (DATE) aDate;
// buff.append(date.stringValue()).append("','MM/DD/YYYY HH24:MI:SS')");
} else {
return null;
}
return buff.toString();
}
/**
* Exchange a date format String into a TO_DATE format string for sql.
* The exchange principle is following an Oracle way
*
* @param str Date formate string , i.e. 2005-09-28 14:30
* @param patten oracle date patten
* Parameter Explanation
* YEAR Year, spelled out
* YYYY 4-digit year
* YYY
* YY
* Y Last 3, 2, or 1 digit(s) of year.
* IYY
* IY
* I Last 3, 2, or 1 digit(s) of ISO year.
* IYYY 4-digit year based on the ISO standard
* RRRR Accepts a 2-digit year and returns a 4-digit year.
* A value between 0-49 will return a 20xx year.
* A value between 50-99 will return a 19xx year.
* Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
* MM Month (01-12; JAN = 01).
* MON Abbreviated name of month.
* MONTH Name of month, padded with blanks to length of 9
* characters.
* RM Roman numeral month (I-XII; JAN = I).
* WW Week of year (1-53) where week 1 starts on the first day
* of the year and continues to the seventh day of the year.
* W Week of month (1-5) where week 1 starts on the first day
* of the month and ends on the seventh.
* IW Week of year (1-52 or 1-53) based on the ISO standard.
* D Day of week (1-7).
* DAY Name of day.
* DD Day of month (1-31).
* DDD Day of year (1-366).
* DY Abbreviated name of day.
* J Julian day; the number of days since January 1, 4712 BC.
* HH Hour of day (1-12).
* HH12 Hour of day (1-12).
* HH24 Hour of day (0-23).
* MI Minute (0-59).
* SS Second (0-59).
* SSSSS Seconds past midnight (0-86399).
* AM, A.M.,
* PM, or P.M.
* AD or A.D AD indicator
* BC or B.C. BC indicator
* TZD Daylight savings information. For example, 'PST'
* TZH Time zone hour.
* TZM Time zone minute.
* TZR Time zone region.
* Usage example:
* toOracleDateFormat("2003/07/09","yyyy/mm/dd") returns TO_DATE('2003/07/09', 'yyyy/mm/dd')
* @return
*/
public static String toOracleDateFormat(String str, String patten) {
return "TO_DATE('" + str + "','" + patten + "')";
}
/**
* Parse a date format string into a java.util.Date object
*
* @param dateStr Date string
* @param dateFmt Date format to parse the string
* @return
* @throws ParseException If the string and the format is not match, exception will be thrown
*/
public static Date toUtilDate(String dateStr, String dateFmt) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(dateFmt);
return format.parse(dateStr);
}
public static Date toUtilDateN(String dateStr, String dateFmt) {
try {
SimpleDateFormat format = new SimpleDateFormat(dateFmt);
return format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* Exchange day format string like yyyy-MM-dd HH:mm into a java.util.Date
*
* @param dateStr
* @return
* @throws ParseException
*/
public static Date toDefaultDateTime(String dateStr) throws ParseException {
Date date = null;
try {
date = toUtilDate(dateStr.trim(), DEFAULT_DATE_TIME);
} catch (ParseException e) {
date = toUtilDate(dateStr.trim(), DEFAULT_DATE);
}
return date;
}
/**
* Exchange day format string like yyyy-MM-dd HH into a java.util.Date
*
* @param dateStr
* @return
* @throws ParseException
*/
public static Date toDefaultDateTimeHour(String dateStr) throws ParseException {
Date date = null;
try {
date = toUtilDate(dateStr.trim(), DEFAULT_DATE_TIME_HOUR);
} catch (ParseException e) {
date = toUtilDate(dateStr.trim(), DEFAULT_DATE);
}
return date;
}
/**
* Exchange day format string like yyyy-MM-dd HH:mm into a java.util.Date
*
* @param dateStr
* @return
* @throws ParseException
*/
public static Date toDefaultDateTimeSecond(String dateStr) throws ParseException {
Date date = null;
try {
date = toUtilDate(dateStr.trim(), DEFAULT_DATE_TIME_SECOND);
} catch (ParseException e) {
date = toUtilDate(dateStr.trim(), DEFAULT_DATE);
}
return date;
}
/**
* Exchange day format string like yyyy-MM-dd into a java.util.Date
*
* @param date
* @return String
*/
public static String parseToDefaultDateSecondString(Date date) {
return parseToFormatDateString(date, DEFAULT_DATE_TIME_SECOND);
}
/**
* Exchange day format string like yyyy-MM-dd into a java.util.Date
*
* @param dateStr
* @return
* @throws ParseException
*/
public static Date toDefaultDate(String dateStr) throws ParseException {
return toUtilDate(dateStr, DEFAULT_DATE);
}
public static Date toDefaultDateValue(String dateStr) {
try {
return toUtilDate(dateStr, DEFAULT_DATE);
}catch (Exception e){
logger.error("<toDefaultDateValue> ", e);
}
return null;
}
/**
* Exchange day format string like HH:mm into a java.util.Date
*
* @param dateStr
* @return
* @throws ParseException
*/
public static Date toDefaultTime(String dateStr) throws ParseException {
return toUtilDate(dateStr, DEFAULT_TIME);
}
/**
* Merge the date and the time into one java.util.Date object
*
* @param date Date
* @param time Time
* @return A java.util.Date object containing the date and the time
*/
public static Date mergeDateAndTime(Date date, Date time) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
//split the date into year, month and day
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(time);
cal.set(year, month, day);
return cal.getTime();
}
/**
* Exchange the java.util.Date object into the DEFAULT_DATE_TIME formate string
*
* @param date
* @return
*/
public static String parseToDefaultDateTimeString(Date date) {
return parseToFormatDateString(date, DEFAULT_DATE_TIME);
}
/**
* Exchange the java.util.Date object into the DEFAULT_DATE formate string
*
* @param date
* @return
*/
public static String parseToDefaultDateString(Date date) {
return parseToFormatDateString(date, DEFAULT_DATE);
}
/**
* Exchange the java.util.Date object into the DEFAULT_TIME formate string
*
* @param date
* @return
*/
public static String parseToDefaultTimeString(java.util.Date date) {
return parseToFormatDateString(date, DEFAULT_TIME);
}
public static String parseToHMSTime(java.util.Date date) {
return parseToFormatDateString(date, DEFAULT_TIME_HMS);
}
public static String parseToFormatDateString(Date date, String patten) {
SimpleDateFormat format = new SimpleDateFormat(patten);
if (date != null) {
return format.format(date);
} else {
return "";
}
}
public static String parseToTimeStamp(Date date){
SimpleDateFormat format = new SimpleDateFormat(TIME_STAMP);
if(date != null){
return format.format(date);
}else{
return "";
}
}
public static String parseToTimeStamp2(Date date){
SimpleDateFormat format = new SimpleDateFormat(TIME_STAMP_2);
if(date != null){
return format.format(date);
}else{
return "";
}
}
public static String parseToTradeTimeStamp(Date date){
SimpleDateFormat format = new SimpleDateFormat(TRADE_TIME_STAMP);
if(date != null){
return format.format(date);
}else{
return "";
}
}
public static String parseToYMDTimeStamp(Date date){
SimpleDateFormat format = new SimpleDateFormat(YMD_TIME_STAMP);
if(date != null){
return format.format(date);
}else{
return "";
}
}
public static String parseToYMDTimeStamp2(Date date){
SimpleDateFormat format = new SimpleDateFormat(YMD_TIME_STAMP2);
if(date != null){
return format.format(date);
}else{
return "";
}
}
/**
* Compare two java.util.Date object in date field(year, month and day)
*
* @param date1
* @param date2
* @return If the two Date object are the same day, return true
*/
public static boolean isDateEqual(Date date1, Date date2) {
if (date1 == null || date2 == null)
//one of the input is null, skip the comparation
return false;
boolean rtnVal = true;
Calendar cal1 = new GregorianCalendar();
cal1.setTime(date1);
Calendar cal2 = new GregorianCalendar();
cal2.setTime(date2);
//compare year
rtnVal = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
//compare day
if (rtnVal)
//if two dates are in the same year, compare them with the day
rtnVal = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
return rtnVal;
}
/**
* Compare two date in time zone(hour,minute,no need to compare for second
* for it is useless)
*
* @param date1
* @param date2
* @return true if the two date are the same in hour and minute
*/
public static final boolean isTimeEqual(Date date1, Date date2) {
boolean rtnVal = true;
Calendar cal1 = new GregorianCalendar();
cal1.setTime(date1);
Calendar cal2 = new GregorianCalendar();
cal1.setTime(date2);
rtnVal = cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY);
if (rtnVal)
rtnVal = cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE);
return rtnVal;
}
/**
* Test whether a date is within an date range
*
* @param date The date to be test
* @param from From range
* @param to To range
* @return
*/
public static final boolean isBetween(Date date, Date from, Date to) {
return from.before(date) && to.after(date);
}
/**
* Get the day of tomorrow.
*
* @param date Date
* @return Date
*/
public static Date getTomorrow(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
/**
* Get the day of yesterday.
*
* @return Date
*/
public static Date getYesterday() {
return add(new Date(), -1);
}
/**
* 获取中国农历年信息.
*
* @param date 公历日期
* @return ChineseYear 农历年信息
*/
public static ChineseYear getChineseYear(Date date) {
return new ChineseYear(date);
}
/**
* 返回生肖.
*
* @param date 公历生日
* @return 生肖名
*/
public static String getAnimalName(Date date) {
ChineseYear year = new ChineseYear(date);
try {
return year.getAnimalName();
} finally {
year = null; //release resources
}
}
/**
* 返回生肖代号.
*
* @param date 公历生日
* @return 生肖名
*/
public static Integer getAnimalCode(Date date) {
ChineseYear year = new ChineseYear(date);
try {
return new Integer(year.getAnimalCode().intValue() + 1);
} finally {
year = null; //release resources
}
}
/**
* 中国农历类.
* <p/>
* 装载农历年月日和生肖等信息,如果是闰月,则显示月份会用-好显示,但是在toString()方法中
* 会转换为可直接输出的"闰"字
* </p>
* <p>Created by 2006-10-8</p>
*
* @author <a href="mailto:[email protected]">Watson</a>
*/
static class ChineseYear {
private int chineseYear;
private int chineseMonth;
private int chineseDay;
public ChineseYear(Date date) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; //Calendar类的月份从0开始,运算月份从1开始,故要加1
int day = cal.get(Calendar.DAY_OF_MONTH);
if (year < 1901 || year > 2100) {
throw new IllegalArgumentException("Year must between from 1901 to 2100");
}
int startYear = 1901;
int startMonth = 1;
int startDay = 1;
chineseYear = 4597;
chineseMonth = 11;
chineseDay = 11;
// 第二个对应日,用以提高计算效率
// 公历 2000 年 1 月 1 日,对应农历 4697 年 11 月 25 日
if (year >= 2000) {
startYear = 2000;
startMonth = 1;
startDay = 1;
chineseYear = 4696;
chineseMonth = 11;
chineseDay = 25;
}
//计算与基准日的天数差距
int daysDiff = 0;
for (int i = startYear; i < year; i++) {
daysDiff += 365;
if (isGregorianLeapYear(i)) daysDiff += 1; // leap year
}
for (int i = startMonth; i < month; i++) {
daysDiff += daysInGregorianMonth(year, i);
}
daysDiff += day - startDay;
//计算农历日
chineseDay += daysDiff;
int lastDay = daysInChineseMonth(chineseYear, chineseMonth);
int nextMonth = nextChineseMonth(chineseYear, chineseMonth);
while (chineseDay > lastDay) {
if (Math.abs(nextMonth) < Math.abs(chineseMonth)) chineseYear++;
chineseMonth = nextMonth;
chineseDay -= lastDay;
lastDay = daysInChineseMonth(chineseYear, chineseMonth);
nextMonth = nextChineseMonth(chineseYear, chineseMonth);
}
}
public String getAnimalName() {
return animalNames[(chineseYear - 1) % 12];
}
public Integer getAnimalCode() {
return new Integer(((chineseYear - 1) % 12));
}
public String toString() {
StringBuffer buff = new StringBuffer();
buff.append(stemNames[(chineseYear - 1) % 10]); //天干纪年
buff.append(branchNames[(chineseYear - 1) % 12]).append("年 "); //地支纪年
if (chineseMonth < 0) {
buff.append("闰");
}
buff.append(monthNames[Math.abs(chineseMonth) - 1]).append("月");
buff.append(dayNames[chineseDay - 1]);
String show = buff.toString();
buff = null;
return show;
}
//天干
private final static String[] stemNames = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
//地支
private final static String[] branchNames = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
//月份中文名
private final static String[] monthNames = {"正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "冬", "腊"};
private final static String[] dayNames = {"初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
"十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
"廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十",};
//生肖名
private static String[] animalNames = {"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"};
//大闰月的闰年年份
private final static int[] bigLeapMonthYears = {
6, 14, 19, 25, 33, 36, 38, 41, 44, 52,
55, 79, 117, 136, 147, 150, 155, 158, 185, 193
};
private final static char[] daysInGregorianMonth =
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
private final static char[] chineseMonths = {
// 农历月份大小压缩表,两个字节表示一年。两个字节共十六个二进制位数,
// 前四个位数表示闰月月份,后十二个位数表示十二个农历月份的大小。
0x00, 0x04, 0xad, 0x08, 0x5a, 0x01, 0xd5, 0x54, 0xb4, 0x09, 0x64, 0x05, 0x59, 0x45,
0x95, 0x0a, 0xa6, 0x04, 0x55, 0x24, 0xad, 0x08, 0x5a, 0x62, 0xda, 0x04, 0xb4, 0x05,
0xb4, 0x55, 0x52, 0x0d, 0x94, 0x0a, 0x4a, 0x2a, 0x56, 0x02, 0x6d, 0x71, 0x6d, 0x01,
0xda, 0x02, 0xd2, 0x52, 0xa9, 0x05, 0x49, 0x0d, 0x2a, 0x45, 0x2b, 0x09, 0x56, 0x01,
0xb5, 0x20, 0x6d, 0x01, 0x59, 0x69, 0xd4, 0x0a, 0xa8, 0x05, 0xa9, 0x56, 0xa5, 0x04,
0x2b, 0x09, 0x9e, 0x38, 0xb6, 0x08, 0xec, 0x74, 0x6c, 0x05, 0xd4, 0x0a, 0xe4, 0x6a,
0x52, 0x05, 0x95, 0x0a, 0x5a, 0x42, 0x5b, 0x04, 0xb6, 0x04, 0xb4, 0x22, 0x6a, 0x05,
0x52, 0x75, 0xc9, 0x0a, 0x52, 0x05, 0x35, 0x55, 0x4d, 0x0a, 0x5a, 0x02, 0x5d, 0x31,
0xb5, 0x02, 0x6a, 0x8a, 0x68, 0x05, 0xa9, 0x0a, 0x8a, 0x6a, 0x2a, 0x05, 0x2d, 0x09,
0xaa, 0x48, 0x5a, 0x01, 0xb5, 0x09, 0xb0, 0x39, 0x64, 0x05, 0x25, 0x75, 0x95, 0x0a,
0x96, 0x04, 0x4d, 0x54, 0xad, 0x04, 0xda, 0x04, 0xd4, 0x44, 0xb4, 0x05, 0x54, 0x85,
0x52, 0x0d, 0x92, 0x0a, 0x56, 0x6a, 0x56, 0x02, 0x6d, 0x02, 0x6a, 0x41, 0xda, 0x02,
0xb2, 0xa1, 0xa9, 0x05, 0x49, 0x0d, 0x0a, 0x6d, 0x2a, 0x09, 0x56, 0x01, 0xad, 0x50,
0x6d, 0x01, 0xd9, 0x02, 0xd1, 0x3a, 0xa8, 0x05, 0x29, 0x85, 0xa5, 0x0c, 0x2a, 0x09,
0x96, 0x54, 0xb6, 0x08, 0x6c, 0x09, 0x64, 0x45, 0xd4, 0x0a, 0xa4, 0x05, 0x51, 0x25,
0x95, 0x0a, 0x2a, 0x72, 0x5b, 0x04, 0xb6, 0x04, 0xac, 0x52, 0x6a, 0x05, 0xd2, 0x0a,
0xa2, 0x4a, 0x4a, 0x05, 0x55, 0x94, 0x2d, 0x0a, 0x5a, 0x02, 0x75, 0x61, 0xb5, 0x02,
0x6a, 0x03, 0x61, 0x45, 0xa9, 0x0a, 0x4a, 0x05, 0x25, 0x25, 0x2d, 0x09, 0x9a, 0x68,
0xda, 0x08, 0xb4, 0x09, 0xa8, 0x59, 0x54, 0x03, 0xa5, 0x0a, 0x91, 0x3a, 0x96, 0x04,
0xad, 0xb0, 0xad, 0x04, 0xda, 0x04, 0xf4, 0x62, 0xb4, 0x05, 0x54, 0x0b, 0x44, 0x5d,
0x52, 0x0a, 0x95, 0x04, 0x55, 0x22, 0x6d, 0x02, 0x5a, 0x71, 0xda, 0x02, 0xaa, 0x05,
0xb2, 0x55, 0x49, 0x0b, 0x4a, 0x0a, 0x2d, 0x39, 0x36, 0x01, 0x6d, 0x80, 0x6d, 0x01,
0xd9, 0x02, 0xe9, 0x6a, 0xa8, 0x05, 0x29, 0x0b, 0x9a, 0x4c, 0xaa, 0x08, 0xb6, 0x08,
0xb4, 0x38, 0x6c, 0x09, 0x54, 0x75, 0xd4, 0x0a, 0xa4, 0x05, 0x45, 0x55, 0x95, 0x0a,
0x9a, 0x04, 0x55, 0x44, 0xb5, 0x04, 0x6a, 0x82, 0x6a, 0x05, 0xd2, 0x0a, 0x92, 0x6a,
0x4a, 0x05, 0x55, 0x0a, 0x2a, 0x4a, 0x5a, 0x02, 0xb5, 0x02, 0xb2, 0x31, 0x69, 0x03,
0x31, 0x73, 0xa9, 0x0a, 0x4a, 0x05, 0x2d, 0x55, 0x2d, 0x09, 0x5a, 0x01, 0xd5, 0x48,
0xb4, 0x09, 0x68, 0x89, 0x54, 0x0b, 0xa4, 0x0a, 0xa5, 0x6a, 0x95, 0x04, 0xad, 0x08,
0x6a, 0x44, 0xda, 0x04, 0x74, 0x05, 0xb0, 0x25, 0x54, 0x03
};
private boolean isGregorianLeapYear(int year) {
boolean isLeap = false;
if (year % 4 == 0) isLeap = true;
if (year % 100 == 0) isLeap = false;
if (year % 400 == 0) isLeap = true;
return isLeap;
}
/*
* 计算农历日期
*/
private int daysInChineseMonth(int y, int m) {
// 注意:闰月 m < 0
int index = y - 4597;
int v = 0;
int l = 0;
int d = 30;
if (1 <= m && m <= 8) {
v = chineseMonths[2 * index];
l = m - 1;
if (((v >> l) & 0x01) == 1)
d = 29;
} else if (9 <= m && m <= 12) {
v = chineseMonths[2 * index + 1];
l = m - 9;
if (((v >> l) & 0x01) == 1)
d = 29;
} else {
v = chineseMonths[2 * index + 1];
v = (v >> 4) & 0x0F;
if (v != Math.abs(m)) {
d = 0;
} else {
d = 29;
for (int i = 0; i < bigLeapMonthYears.length; i++) {
if (bigLeapMonthYears[i] == index) {
d = 30;
break;
}
}
}
}
return d;
}
/*
* 计算下一个农历月的日期
*/
private int nextChineseMonth(int y, int m) {
int n = Math.abs(m) + 1;
if (m > 0) {
int index = y - 4597;
int v = chineseMonths[2 * index + 1];
v = (v >> 4) & 0x0F;
if (v == m) n = -m;
}
if (n == 13) n = 1;
return n;
}
/*
* 计算公历月份
*/
private int daysInGregorianMonth(int y, int m) {
int d = daysInGregorianMonth[m - 1];
if (m == 2 && isGregorianLeapYear(y)) d++; // 公历闰年二月多一天
return d;
}
}
/**
* 星座处理
*
* @param date
* @return
*/
public static Integer getConstellation(Date date) throws Exception {
if (null == date)
throw new NullPointerException("日期参数为空");
if ((isDateInRange(date, new Date(date.getYear(), 11, 22), new Date(date.getYear(), 11, 31))) || (isDateInRange(date, new Date(date.getYear(), 0, 1), new Date(date.getYear(), 0, 19))))
return ConstellationConstants.CAPRICORN;
else if (isDateInRange(date, new Date(date.getYear(), 0, 20), new Date(date.getYear(), 1, 18)))
return ConstellationConstants.AQUARIUS;
else if (isDateInRange(date, new Date(date.getYear(), 1, 19), new Date(date.getYear(), 2, 20)))
return ConstellationConstants.PISCES;
else if (isDateInRange(date, new Date(date.getYear(), 2, 21), new Date(date.getYear(), 3, 20)))
return ConstellationConstants.ARIES;
else if (isDateInRange(date, new Date(date.getYear(), 3, 21), new Date(date.getYear(), 4, 20)))
return ConstellationConstants.TAURUS;
else if (isDateInRange(date, new Date(date.getYear(), 4, 21), new Date(date.getYear(), 5, 21)))
return ConstellationConstants.GEMINI;
else if (isDateInRange(date, new Date(date.getYear(), 5, 22), new Date(date.getYear(), 6, 22)))
return ConstellationConstants.CANCER;
else if (isDateInRange(date, new Date(date.getYear(), 6, 23), new Date(date.getYear(), 7, 22)))
return ConstellationConstants.LEO;
else if (isDateInRange(date, new Date(date.getYear(), 7, 23), new Date(date.getYear(), 8, 22)))
return ConstellationConstants.VIRGO;
else if (isDateInRange(date, new Date(date.getYear(), 8, 23), new Date(date.getYear(), 9, 22)))
return ConstellationConstants.LIBRA;
else if (isDateInRange(date, new Date(date.getYear(), 9, 23), new Date(date.getYear(), 10, 21)))
return ConstellationConstants.SCORPIO;
else if (isDateInRange(date, new Date(date.getYear(), 10, 22), new Date(date.getYear(), 11, 21)))
return ConstellationConstants.ARCHER;
throw new Exception("星座转换出错");
}
/**
* 判断 date是否大于等于开始日期,小于等于结束日期
*
* @param date 指定某个日期
* @param from 开始日期
* @param to 结束日期
* @return
* @author: zhanghailang
*/
public static boolean isDateInRange(Date date, Date from, Date to) {
if ((date.after(from) && date.before(to)) || date.compareTo(from) == 0 || date.compareTo(to) == 0) {
return true;
} else
return false;
}
/**
*
*/
public static String getLastLoginTimeString(Date lastSignonTime) {
int day = daysBetween(new Date(), lastSignonTime);
String lastLoginTime = "";
if (day <= 1)
lastLoginTime = "24小时内";
if (day > 1 && day <= 3)
lastLoginTime = "3天内";
else if (day > 3 && day <= 7)
lastLoginTime = "1个星期内";
else if (day > 7 && day <= 15)
lastLoginTime = "半个月内";
else if (day > 15)
lastLoginTime = "半月以上";
return lastLoginTime;