Java編寫的日期計算方法

 

 

本身用Java編寫的時間獲取類,目前應用在數據交換監控系統中,經測試能夠正常使用。java

提供如下功能:測試

Time tt = new Time();
System.out.println("獲取昨天日期:" + tt.getyd());
System.out.println("獲取當天日期:" + tt.getNowTime("yyyy-MM-dd"));
System.out.println("獲取本週一日期:" + tt.getMondayOFWeek());
System.out.println("獲取本週日的日期:" + tt.getCurrentWeekday());
System.out.println("獲取上週一日期:" + tt.getPreviousWeekday(-1));////----------
System.out.println("獲取上週日日期:" + tt.getPreviousWeekSunday(-1));///-------------
System.out.println("獲取本月第一天日期:" + tt.getFirstDayOfMonth());
System.out.println("獲取本月最後一天日期:" + tt.getDefaultDay());
System.out.println("獲取上月第一天日期:" + tt.getPreviousMonthFirst(-1));///------------
System.out.println("獲取上月最後一天的日期:" + tt.getPreviousMonthEnd(-1));///---------
System.out.println("前一個小時"+tt.getFixedHour(-1));
System.out.println("前五分鐘"+tt.getFixedMinute(-5));
System.out.println("前20秒"+tt.getFixedSecond(-20));
System.out.println("兩個日期相差多少天"+tt.daysBetween("2015-07-08","2015-07-10"));
System.out.println(" 計算指定日期的先後幾天"+tt.getFixedDayfromDay("2015-07-08",1));spa

 

import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


public class Time
{
  public static  void main(String[] args) throws ParseException
  {
    Time tt = new Time();
    System.out.println("獲取昨天日期:" + tt.getyd());
    System.out.println("獲取當天日期:" + tt.getNowTime("yyyy-MM-dd"));
    System.out.println("獲取本週一日期:" + tt.getMondayOFWeek());
    System.out.println("獲取本週日的日期:" + tt.getCurrentWeekday());
    System.out.println("獲取上週一日期:" + tt.getPreviousWeekday(-1));////----------
    System.out.println("獲取上週日日期:" + tt.getPreviousWeekSunday(-1));///-------------
    System.out.println("獲取本月第一天日期:" + tt.getFirstDayOfMonth());
    System.out.println("獲取本月最後一天日期:" + tt.getDefaultDay());
    System.out.println("獲取上月第一天日期:" + tt.getPreviousMonthFirst(-1));///------------
    System.out.println("獲取上月最後一天的日期:" + tt.getPreviousMonthEnd(-1));///---------
    System.out.println("前一個小時"+tt.getFixedHour(-1));
    System.out.println("前五分鐘"+tt.getFixedMinute(-5));
    System.out.println("前20秒"+tt.getFixedSecond(-20));
    System.out.println("兩個日期相差多少天"+tt.daysBetween("2015-07-08","2015-07-10"));
    System.out.println(" 計算指定日期的先後幾天"+tt.getFixedDayfromDay("2015-07-08",1));
    
    
  }

  
  /**
   * 計算兩個日期相差多少天
   * @param smdate
   * 起始日期 yyyy-MM-dd
   * @param bdate
   * 截止日期 yyyy-MM-dd
   * @return
   */
  public  int daysBetween(String smdate,String bdate)  {  
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
      Calendar cal = Calendar.getInstance();    
      try {
        cal.setTime(sdf.parse(smdate));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }    
      long time1 = cal.getTimeInMillis();                 
      try {
        cal.setTime(sdf.parse(bdate));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }    
      long time2 = cal.getTimeInMillis();         
      long between_days=(time2-time1)/(1000*3600*24);  
          
     return Integer.parseInt(String.valueOf(between_days));     
  }  
  

  /**
   * 獲取sdate這一天是星期幾
   * @param sdate
   * @return
   */
  public  String getWeek(String sdate)
  {
    Date date = strToDate(sdate);


    Calendar c = Calendar.getInstance();


    c.setTime(date);


    return new SimpleDateFormat("EEEE").format(c.getTime());
  }


  public  Date strToDate(String strDate)
  {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");


    ParsePosition pos = new ParsePosition(0);


    Date strtodate = formatter.parse(strDate, pos);


    return strtodate;
  }


  /**
   * 獲取date1與date2之間天數的差值
   * 當date1在前時,差值爲負;當date2在前時,差值爲正
   * @param date1
   * @param date2
   * @return
   */
  public  long getDays(String date1, String date2)
  {
    if ((date1 == null) || (date1.equals("")))
    {
      return 0L;
    }
    if ((date2 == null) || (date2.equals("")))
    {
      return 0L;
    }


    SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");


    Date date = null;


    Date mydate = null;
    try
    {
      date = myFormatter.parse(date1);


      mydate = myFormatter.parse(date2);
    }
    catch (Exception localException)
    {
    }


    long day = (date.getTime() - mydate.getTime()) / 86400000L;


    return day;
  }


  /**
   * 獲取昨天日期
   * @return
   */
  public String getyd()
  {
    Calendar cal = Calendar.getInstance();
    cal.add(5, -1);
    String yesterday = new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
    return yesterday;
  }

/**
 * 獲取本月最後一天日期
 * @return
 */
  public String getDefaultDay()
  {
    String str = "";


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    Calendar lastDate = Calendar.getInstance();


    lastDate.set(5, 1);


    lastDate.add(2, 1);


    lastDate.add(5, -1);


    str = sdf.format(lastDate.getTime());


    return str;
  }


  /**
   * 獲取前n月第一天日期,n爲負數
   * @return
   */
  public String getPreviousMonthFirst(int n)
  {
    String str = "";


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    Calendar lastDate = Calendar.getInstance();


    lastDate.set(5, 1);


    lastDate.add(Calendar.MONTH, n);


    str = sdf.format(lastDate.getTime());


    return str;
  }

/**
 * "獲取本月第一天日期
 * @return
 */
  public String getFirstDayOfMonth()
  {
    String str = "";


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    Calendar lastDate = Calendar.getInstance();


    lastDate.set(5, 1);


    str = sdf.format(lastDate.getTime());


    return str;
  }

/**
 *獲取本週日的日期
 * @return
 */
  public String getCurrentWeekday()
  {
    int weeks = 0;


    int mondayPlus = getMondayPlus();


    GregorianCalendar currentDate = new GregorianCalendar();


    currentDate.add(5, mondayPlus + 6);


    Date monday = currentDate.getTime();


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    String preMonday = sdf.format(monday);


    return preMonday;
  }

/**
 * 獲取當天日期
 * @param dateformat
 * @return
 */
  public String getNowTime(String dateformat)
  {
    Date now = new Date();


    SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);


    String hehe = dateFormat.format(now);


    return hehe;
  }


  private int getMondayPlus()
  {
    Calendar cd = Calendar.getInstance();


    int dayOfWeek = cd.get(7) - 1;


    if (dayOfWeek == 1)
    {
      return 0;
    }


    return (1 - dayOfWeek);
  }

/**
 * 獲取本週一日期
 * @return
 */
  public String getMondayOFWeek()
  {
    int weeks = 0;


    int mondayPlus = getMondayPlus();


    GregorianCalendar currentDate = new GregorianCalendar();


    currentDate.add(5, mondayPlus);


    Date monday = currentDate.getTime();


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    String preMonday = sdf.format(monday);


    return preMonday;
  }

/**
 * 獲取前n週週日日期,n爲負數
 * @return
 */
  public String getPreviousWeekSunday(int n)
  {


    int weeks = n;


    int mondayPlus = getMondayPlus();


    GregorianCalendar currentDate = new GregorianCalendar();


    currentDate.add(5, mondayPlus + weeks);


    Date monday = currentDate.getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String preMonday = sdf.format(monday);


    return preMonday;
  }


  /**
   * 獲取前n週週一的日期,n爲負數
   * @return
   */
  public String getPreviousWeekday(int n)
  {
      
int weeks=n;
      
    int mondayPlus = getMondayPlus();


    GregorianCalendar currentDate = new GregorianCalendar();


    currentDate.add(5, mondayPlus + 7 * weeks);


    Date monday = currentDate.getTime();


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    String preMonday = sdf.format(monday);


    return preMonday;
  }

/**
 * 獲取前n月最後一天的日期,n爲負數
 * @return
 */
  public String getPreviousMonthEnd(int n)
  {
    String str = "";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar lastDate = Calendar.getInstance();
    lastDate.add(2, n);
    lastDate.set(5, 1);
    lastDate.roll(5, -1);
    str = sdf.format(lastDate.getTime());
    return str;
  }
  
  
  /**
   * 獲取當前日期的前dayCount天的日期
   * @param dayCount
   * @return
   * yyyy-MM-dd
   */
  public  String getFixedDay(int dayCount)
    {
        Format f = new SimpleDateFormat("yyyy-MM-dd");
         Calendar c = Calendar.getInstance();
        // c = day(c, dayCount);
         c.add(Calendar.DATE, dayCount);
         return f.format(c.getTime());
    }
  
  
  /**
   * 計算指定日期的先後幾天
   * @param day 
   * yyyy-MM-dd
   * @param count
   * @return
   * yyyy-MM-dd
   * @throws ParseException
   */
  public String getFixedDayfromDay(String day,int count) throws ParseException
  {

          SimpleDateFormat   sdf=new   SimpleDateFormat( "yyyy-MM-dd"); 
        Date dt = sdf.parse(day ,new   ParsePosition(0));
        Calendar   rightNow   =   Calendar.getInstance(); 
        rightNow.setTime(dt); 
        rightNow.add(Calendar.DATE,count);//你要加減的日期   
        Date   dt1=rightNow.getTime(); 
        String   reStr=sdf.format(dt1); 
       
      
      return reStr;
  }
  
  /**
   * 獲取當前時間的前、後hourCount(小時)的時間
   * @param hourCount
   * @return
   */
  public String getFixedHour(int hourCount)
  {
      Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Calendar c = Calendar.getInstance();
        // c = day(c, dayCount);
         c.add(Calendar.HOUR, hourCount);
         return f.format(c.getTime());
  }
  
  
  /**
   * 獲取當前時間的前、後minuteCount(分鐘)的時間
   * @param minuteCount
   * @return
   */
  public String getFixedMinute(int minuteCount)
  {
      Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Calendar c = Calendar.getInstance();
        // c = day(c, dayCount);
         c.add(Calendar.MINUTE, minuteCount);
         return f.format(c.getTime());
  }
  
  
  /**
   * 獲取當前時間的前、後secondCount(秒)的時間
   * @param secondCount
   * @return
   */
  public String getFixedSecond(int secondCount)
  {
      Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Calendar c = Calendar.getInstance();
        // c = day(c, dayCount);
         c.add(Calendar.SECOND, secondCount);
         return f.format(c.getTime());
  }
}
相關文章
相關標籤/搜索