DateUtil.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package cn.com.free.util;
  2. import java.text.SimpleDateFormat;
  3. import java.util.ArrayList;
  4. import java.util.Calendar;
  5. import java.util.Date;
  6. import java.util.List;
  7. public class DateUtil {
  8. /**
  9. * 取得当前年份
  10. *
  11. * @author zbq
  12. * @date 2010-01-29
  13. */
  14. public static String getCurrentYear(){
  15. SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
  16. Date date = new Date();
  17. return sdf.format(date);
  18. }
  19. /**
  20. * 取得年月日时分秒
  21. *
  22. * @author zbq
  23. * @date 2010-01-29
  24. */
  25. public static String getCurrentTime(){
  26. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  27. Date date = new Date();
  28. return sdf.format(date);
  29. }
  30. /**
  31. * 取得年月日时分秒
  32. *
  33. * @author zbq
  34. * @date 2010-01-29
  35. */
  36. public static String getYmdSfm(){
  37. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  38. Date date = new Date();
  39. return sdf.format(date);
  40. }
  41. /**
  42. * 取得当前日期字符串
  43. *
  44. * @return YYYYMMDD(例:20110829)
  45. *
  46. * @Author zbq
  47. * @Date 2011-8-30
  48. */
  49. public static String getTodayYmd() {
  50. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  51. Date date = new Date();
  52. return sdf.format(date);
  53. }
  54. /**
  55. * 取得一周日期
  56. *
  57. * @author zbq
  58. * @date 2010-01-29
  59. */
  60. public static List<String> getDateToWeek(Date date){
  61. List<String> dateWeekList = new ArrayList<String>();
  62. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  63. String time = "";
  64. //flag用来存取与当天日期的相差数
  65. int flag = 0;
  66. for(int i=1;i<8;i++){
  67. //新建日历
  68. Calendar cal = Calendar.getInstance();
  69. //在日历中找到当前日期
  70. cal.setTime(date);
  71. //当前日期时本周第几天,默认按照西方惯例上周星期天为第一天
  72. flag = -cal.get(Calendar.DAY_OF_WEEK);
  73. //根据循环。当天与上周星期天和本周一到周五相差的天数
  74. cal.add(Calendar.DATE, flag+i);
  75. //转化格式
  76. time = sdf.format(cal.getTime());
  77. //存入list
  78. dateWeekList.add(time);
  79. }
  80. return dateWeekList;
  81. }
  82. /**
  83. * 两个日期比较
  84. *
  85. * @return 比较结果0为相等、小于0为前小于后,大于0为前大于后
  86. *
  87. * @Author zbq
  88. * @Date 2011-8-30
  89. */
  90. public static int getDateTimeCompare(String dateStrStart,String dateStrEnd) {
  91. Calendar c1 = Calendar.getInstance();
  92. Calendar c2 = Calendar.getInstance();
  93. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  94. try {
  95. c2.setTime(sdf.parse(dateStrEnd));
  96. c1.setTime(sdf.parse(dateStrStart));
  97. } catch (java.text.ParseException e) {
  98. }
  99. int result = c1.compareTo(c2);
  100. return result;
  101. }
  102. }