天天看点

java时间管理_JAVA 时间工具类

1 packagecom.XXXXX.XXXXXXX.XXXXXXXX;2

3 importjava.sql.Timestamp;4 importjava.text.DateFormat;5 importjava.text.ParseException;6 importjava.text.SimpleDateFormat;7 importjava.util.Calendar;8 importjava.util.Date;9 importjava.util.StringTokenizer;10 importjava.util.regex.Matcher;11 importjava.util.regex.Pattern;12

13

32

33 public classDateUtil {34 private static final String DATE_PATTERN = "yyyy-MM-dd";35 private static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";36

37

42 public staticString getCurrentDateTime() {43 returngetCurrentDateTime(DATETIME_PATTERN);44 }45

46

52 public staticString getCurrentDate() {53 returngetCurrentDateTime(DATE_PATTERN);54 }55

56

63 public staticString getCurrentDateTime(String pattern) {64 Calendar cal =Calendar.getInstance();65 SimpleDateFormat sdf = newSimpleDateFormat(pattern);66 returnsdf.format(cal.getTime());67 }68

69

76 public static Date getDate(String dateStr) throwsParseException {77 returngetDate(dateStr, DATETIME_PATTERN);78 }79

80

89 public staticDate getDate(String dateStr, String pattern)90 throwsParseException {91 Date date = null;92 SimpleDateFormat dateFormat = newSimpleDateFormat(pattern);93 date =dateFormat.parse(dateStr);94

95 returndate;96 }97

98

105 public staticString getDateString(Date date) {106 returngetString(date, DATE_PATTERN);107 }108

109

116 public staticString getDateTimeString(Date date) {117 returngetString(date, DATETIME_PATTERN);118 }119

120

129 public staticString getString(Date date, String pattern) {130 SimpleDateFormat dateFormat = newSimpleDateFormat(pattern);131

132 returndateFormat.format(date);133 }134

135

141 public staticString formatToDateString(String dateStr)142 throwsParseException {143 returnformatToString(dateStr, DATE_PATTERN);144 }145

146

152 public staticString formatToDateTimeString(String dateTimeStr)153 throwsParseException {154 returnformatToString(dateTimeStr, DATETIME_PATTERN);155 }156

157

166 public staticString formatToString(String dateStr, String pattern)167 throwsParseException {168 dateStr =format(dateStr);169 Date date = null;170 if(checkDateString(dateStr)) {171 date =getDate(dateStr, DATE_PATTERN);172 returngetString(date, pattern);173 } else if(checkDateTimeString(dateStr)) {174 date =getDate(dateStr);175 returngetString(date, pattern);176 } else{177 throw new ParseException("日期格式不正确", 1);178 }179 }180

181

188 public static booleancheckDateString(String dateStr) {189 Pattern pattern = Pattern.compile("\\d{2,4}-\\d{1,2}-\\d{1,2}");190 Matcher matcher =pattern.matcher(dateStr);191

192 returnmatcher.matches();193 }194

195

202 public static booleancheckDateTimeString(String dateTimeStr) {203 Pattern pattern =Pattern204 .compile("\\d{2,4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2}");205 Matcher matcher =pattern.matcher(dateTimeStr);206

207 returnmatcher.matches();208 }209

210

217 public staticString format(String dateStr) {218 Pattern pattern =Pattern219 .compile("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}.*");220 Matcher matcher =pattern.matcher(dateStr);221 if(matcher.matches()) {222 dateStr = dateStr.substring(0, 19);223 } else{224 pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}.*");225 matcher =pattern.matcher(dateStr);226 if(matcher.matches()) {227 dateStr = dateStr.substring(0, 10);228 }229 }230

231 returndateStr;232 }233

234

242 public static intgetYear(Date date) {243 Calendar calendar =Calendar.getInstance();244 calendar.setTime(date);245 int year =calendar.get(Calendar.YEAR);246 returnyear;247 }248

249

257 public static intgetMonth(Date date) {258 Calendar calendar =Calendar.getInstance();259 calendar.setTime(date);260 int month =calendar.get(Calendar.MONTH);261 returnmonth;262 }263

264

272 public static intgetDayOfMonth(Date date) {273 Calendar calendar =Calendar.getInstance();274 calendar.setTime(date);275 int day =calendar.get(Calendar.DAY_OF_MONTH);276 returnday;277 }278

279

287 public static intgetDayOfWek(Date date) {288 Calendar calendar =Calendar.getInstance();289 calendar.setTime(date);290 int day =calendar.get(Calendar.DAY_OF_WEEK);291 returnday;292 }293

294

302 public static intgetHour(Date date) {303 Calendar calendar =Calendar.getInstance();304 calendar.setTime(date);305 int hour =calendar.get(Calendar.HOUR_OF_DAY);306 returnhour;307 }308

309

317 public static intgetMinute(Date date) {318 Calendar calendar =Calendar.getInstance();319 calendar.setTime(date);320 int minute =calendar.get(Calendar.MINUTE);321 returnminute;322 }323

324

332 public static intgetSecond(Date date) {333 Calendar calendar =Calendar.getInstance();334 calendar.setTime(date);335 int second =calendar.get(Calendar.SECOND);336 returnsecond;337 }338

339

346 public staticDate getStartOfDay(Date date) {347 Date startDate = null;348 try{349 startDate =DateUtil.getDate(350 DateUtil.getString(date, "yyyy-MM-dd"), "yyyy-MM-dd");351 } catch(Exception e) {352 return null;353 }354 returnstartDate;355 }356

357

364 public staticDate getEndOfDay(Date date) {365 Calendar calendar =Calendar.getInstance();366 Date endDate = null;367 try{368 calendar.set(DateUtil.getYear(date), DateUtil.getMonth(date),369 DateUtil.getDayOfMonth(date), 23, 59, 59);370 endDate =calendar.getTime();371 } catch(Exception e) {372 return null;373 }374 returnendDate;375 }376

377

384 public staticDate getStartOfWeek(Date date) {385 Calendar calendar =Calendar.getInstance();386 calendar.setTime(date);387 int n = 0;388 int day =calendar.get(Calendar.DAY_OF_WEEK);389 switch(day) {390 caseCalendar.MONDAY: {391 n = 0;392 break;393 }394 caseCalendar.TUESDAY: {395 n = 1;396 break;397 }398 caseCalendar.WEDNESDAY: {399 n = 2;400 break;401 }402 caseCalendar.THURSDAY: {403 n = 3;404 break;405 }406 caseCalendar.FRIDAY: {407 n = 4;408 break;409 }410 caseCalendar.SATURDAY: {411 n = 5;412 break;413 }414 caseCalendar.SUNDAY: {415 n = 6;416 break;417 }418 }419 Date monday = new Date(date.getTime() - 24 * 60 * 60 * 1000 *n);420 Date startDate =getStartOfDay(monday);421 returnstartDate;422 }423

424

431 public staticDate getEndOfWeek(Date date) {432 Calendar calendar =Calendar.getInstance();433 calendar.setTime(date);434 int n = 0;435 int day =calendar.get(Calendar.DAY_OF_WEEK);436 switch(day) {437 caseCalendar.MONDAY: {438 n = 6;439 break;440 }441 caseCalendar.TUESDAY: {442 n = 5;443 break;444 }445 caseCalendar.WEDNESDAY: {446 n = 4;447 break;448 }449 caseCalendar.THURSDAY: {450 n = 3;451 break;452 }453 caseCalendar.FRIDAY: {454 n = 2;455 break;456 }457 caseCalendar.SATURDAY: {458 n = 1;459 break;460 }461 caseCalendar.SUNDAY: {462 n = 0;463 break;464 }465 }466 Date sunday = new Date(date.getTime() + 24 * 60 * 60 * 1000 *n);467 Date startDate =getEndOfDay(sunday);468 returnstartDate;469 }470

471

480 public static longdaysOf2Day(String day1, String day2) {481 try{482 day1 += " 00:00:00";483 day2 += " 00:00:00";484 long secs =secsOf2Day(day1, day2);485 return secs / (24 * 60 * 60);486 } catch(Exception e) {487 return -1;488 }489 }490

491

500 public static longsecsOf2Day(String day1, String day2) {501 try{502 Date date1 =getDate(day1);503 Date date2 =getDate(day2);504 long secs = Math.abs(date1.getTime() - date2.getTime()) / 1000;505 returnsecs;506 } catch(Exception e) {507 return -1;508 }509 }510

511

518 public staticString getDaysToNow(String strDateTime) {519 try{520 StringTokenizer strToken = new StringTokenizer(strDateTime, " ");521 StringTokenizer strTokenDate = newStringTokenizer(522 strToken.nextToken(), "-");523 StringTokenizer strTokenTime = newStringTokenizer(524 strToken.nextToken(), ":");525 int intYear =Integer.parseInt(strTokenDate.nextToken());526 int intMonth = Integer.parseInt(strTokenDate.nextToken()) - 1;527 int intDay =Integer.parseInt(strTokenDate.nextToken());528 int intHour =Integer.parseInt(strTokenTime.nextToken());529 int intMin =Integer.parseInt(strTokenTime.nextToken());530 int intSec =Integer.parseInt(strTokenTime.nextToken());531

532 Calendar cal =Calendar.getInstance();533 cal.set(intYear, intMonth, intDay, intHour, intMin, intSec);534 long longDays = (new Date().getTime() - cal.getTimeInMillis()) / 24

535 / 60 / 60 / 1000;536 longDays = longDays == 0 ? 1: longDays;537

538 return "" +longDays;539 } catch(Exception e) {540 return "0";541 }542 }543

544

553 public static longcompareDatetime(String date1, String date2) {554 DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");555 long timestamp1 = -1;556 long timestamp2 = -1;557 //先将时间格式转换成Timestamp

558 try{559 timestamp1 = df.parse(date1).getTime() / 1000;560 timestamp2 = df.parse(date2).getTime() / 1000;561 } catch(ParseException e) {562 System.out.println("时间格式 [ " + date1 + " ] 或 [ " +date2563 + " ] 无法被解析");564 return -1;565 }566 if (timestamp1 >timestamp2)567 return (timestamp1 - timestamp2) / 3600;568 else

569 return (timestamp2 - timestamp1) / 3600;570

571 }572

573

581 public static Date getDateTimesAfter(String datetimes, intday) {582 Calendar now =Calendar.getInstance();583 try{584 now.setTime(getDate(datetimes, DATETIME_PATTERN));585 } catch(ParseException e) {586 System.out.println("时间格式 [ " + datetimes + " ] 无法被解析");587 return null;588 }589 now.set(Calendar.DATE, now.get(Calendar.DATE) +day);590 returnnow.getTime();591 }592

593

601 public static Date getDateAfter(String datetimes, intday) {602 Calendar now =Calendar.getInstance();603 try{604 now.setTime(getDate(datetimes, DATE_PATTERN));605 } catch(ParseException e) {606 System.out.println("时间格式 [ " + datetimes + " ] 无法被解析");607 return null;608 }609 now.set(Calendar.DATE, now.get(Calendar.DATE) +day);610 returnnow.getTime();611 }612

613

621 public static String getDateBefore(String datetimes, intday) {622 Calendar now =Calendar.getInstance();623 try{624 now.setTime(getDate(datetimes, DATE_PATTERN));625 } catch(ParseException e) {626 System.out.println("时间格式 [ " + datetimes + " ] 无法被解析");627 return null;628 }629 now.set(Calendar.DATE, now.get(Calendar.DATE) -day);630 return getString(now.getTime(), "yyyy-MM-dd");631 }632

633

641 public static String timestampToDate(longtimestamp, String format) {642 Date date = newTimestamp(timestamp);643 DateFormat df = newSimpleDateFormat(format);644 returndf.format(date);645 }646

647

652 public static longdateToTimestamp() {653 long ts =System.currentTimeMillis();654 returnts;655 }656

657

665 public static String getDateTimeAfter(String times, intnum) {666 if (times == null || "".equals(times))667 times =getCurrentDateTime();668

669 long tl = dateToTimestamp(times) + num * 1000;670 return timestampToDate(tl, "yyyy-MM-dd HH:mm:ss");671 }672

673

680 public static longdateToTimestamp(String dateFormat) {681 long timestamp = -1;682 try{683 DateFormat df = newSimpleDateFormat(DATETIME_PATTERN);684 Date date =df.parse(dateFormat);685 timestamp =date.getTime();686 } catch(Exception e) {687 System.out.println("时间格式 [ " + dateFormat + " ] 无法被解析");688 }689 returntimestamp;690 }691

692 public static longcompareDatetime2(String date1, String date2) {693 DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");694 long timestamp1 = -1;695 long timestamp2 = -1;696 //先将时间格式转换成Timestamp

697 try{698 timestamp1 =df.parse(date1).getTime();699 timestamp2 =df.parse(date2).getTime();700 } catch(ParseException e) {701 System.out.println("时间格式 [ " + date1 + " ] 或 [ " +date2702 + " ] 无法被解析");703 return -1;704 }705 if (timestamp1 >timestamp2)706 return (timestamp1 -timestamp2);707 else

708 return (timestamp2 -timestamp1);709

710 }711

712 //对比两个日期大小

713 public static booleancompare_date(String DATE1, String DATE2) {714 DateFormat df = new SimpleDateFormat("yyyy-MM-dd");715 try{716 Date dt1 =df.parse(DATE1);717 Date dt2 =df.parse(DATE2);718 if (dt1.getTime() >dt2.getTime()) {719 //System.out.println("dt1 在dt2前");

720 return false;721 } else if (dt1.getTime()

723 return true;724 } else{725 return true;726 }727 } catch(Exception exception) {728 exception.printStackTrace();729 }730 return true;731 }732

733 public static void main(String[] args) throwsException {734 //System.out.println(getDaysToNow("2010-01-10 00:00:00"));735 //System.out.println(compare_date("2011-05-16 17:50:50","2011-05-16 17:50:55"));736 //System.out.println(getDateTimesAfter("2010-01-10 12:00:00",-5));737 //System.out.println(getDateAfter("2010-01-10",-5));738 //System.out.println(timestampToDate(1262575579707L,"yyyy-MM-dd HH:mm:ss"));

739 System.out.println(compareDatetime("2012-02-02 17:36:46:673",740 "2012-02-03 18:47:37:392"));741

742 //"2010-01-20 17:58:37:319","2010-01-20 18:44:32:592" ibatis + bonecp743 //27ss744 //"2010-01-21 14:51:49:307","2010-01-21 15:47:45:794" hib + c3p0 33ss745 //"2010-01-21 17:36:46:673","2010-01-21 18:47:37:392" ibatis + c3p0746 //42ss747

748 //System.out.println(dateToTimestamp());749 //System.out.println(timestampToDate(1268231397000L-120000,"yyyy-MM-dd HH:mm:ss"));

750

751 System.out.println(DateUtil.getDateString(getDateAfter(752 "2012-02-02 17:36:46", 30)));753 }754 }