日期比较

来源:互联网 发布:ios开发需要学linux 编辑:程序博客网 时间:2024/05/22 03:26
Java代码 复制代码 收藏代码
  1. package test.user.taojq;
  2. import java.text.DateFormat;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Calendar;
  5. import java.util.Collections;
  6. import java.util.Date;
  7. public class Test {
  8. public static void main(String[] argStrings){
  9. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  10. String star=sdf.format(new Date());
  11. String end=sdf.format(new Date(32323232L));
  12. compareDate(star, end, 0);
  13. }
  14. /**
  15. * @param date1 需要比较的时间 不能为空(null),需要正确的日期格式 ,如:2009-09-12
  16. * @param date2 被比较的时间 为空(null)则为当前时间
  17. * @param stype 返回值类型 0为多少天,1为多少个月,2为多少年
  18. * @return
  19. * 举例:
  20. * compareDate("2009-09-12", null, 0);//比较天
  21. * compareDate("2009-09-12", null, 1);//比较月
  22. * compareDate("2009-09-12", null, 2);//比较年
  23. */
  24. public static int compareDate(String startDay,String endDay,int stype){
  25. int n = 0;
  26. String formatStyle = stype==1?"yyyy-MM":"yyyy-MM-dd";
  27. DateFormat df = new SimpleDateFormat(formatStyle);
  28. Calendar c1 = Calendar.getInstance();
  29. Calendar c2 = Calendar.getInstance();
  30. try {
  31. c1.setTime(df.parse(startDay));
  32. c2.setTime(df.parse(endDay));
  33. } catch (Exception e3) {
  34. System.out.println("wrong occured");
  35. }
  36. while (!c1.after(c2)) { // 循环对比,直到相等,n 就是所要的结果
  37. n++;
  38. if(stype==1){
  39. c1.add(Calendar.MONTH, 1); // 比较月份,月份+1
  40. }
  41. else{
  42. c1.add(Calendar.DATE, 1); // 比较天数,日期+1
  43. }
  44. }
  45. n = n-1;
  46. if(stype==2){
  47. n = (int)n/365;
  48. }
  49. return n;
  50. }
  51. public static String getCurrentDate(String format){
  52. Calendar day=Calendar.getInstance();
  53. day.add(Calendar.DATE,0);
  54. SimpleDateFormat sdf=new SimpleDateFormat(format);//"yyyy-MM-dd"
  55. String date = sdf.format(day.getTime());
  56. return date;
  57. }
  58. }  
原创粉丝点击