Java编写的日期计算方法

Posted guaidaoK的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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));

 

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());
  }
}

 

以上是关于Java编写的日期计算方法的主要内容,如果未能解决你的问题,请参考以下文章

java 计算某月有多少天

编写代码片段的更简洁的方法

用JavaScript编写计算日期

常用python日期日志获取内容循环的代码片段

用idea编写java代码时突然出现的问题求大佬指点

求用java编写一个能够完成,对给定日期增加天数的方法