JAVAで日付の増減演算を実現する方法

3040 ワード

JAVAで実現した日付の増減演算方法
一、java.util.Calenderで実現
   Calendar calendar=Calendar.getInstance();   
   calendar.setTime(new Date()); 
   System.out.println(calendar.get(Calendar.DAY_OF_MONTH));                   //       
   calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1); //     1  
   System.out.println(calendar.get(Calendar.DATE));                           //  1     Top 

===============================================================================
二、java.text.SimpleDateFormatとjava.util.Dateで実現
   Date d=new Date();   
   SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
   System.out.println("     :"+df.format(d));   
   System.out.println("      :" + df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000)));  
   System.out.println("      :" + df.format(new Date(d.getTime() + 3 * 24 * 60 * 60 * 1000)));

===============================================================================
GregorianCalendar gc=new GregorianCalendar();  gc.setTime(new Date);  gc.add(field,value);  valueは正則後、負は前  Fieldは1プラス1年、2プラス半年、3プラス1四半期、4プラス1週間  取5加一日....
===============================================================================
/*
*java         
*gc.add(1,-1)      .
*gc.add(2,-1)      .
*gc.add(3.-1)     .
*gc.add(5,-1)     .
*              .    .      .
*GregorianCalendar  add(int field,int amount)         .
*field     , .  .
*amount          .
*
* UseDate.java     :
*/
package temp.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
public class UseDate {

Date d=new Date();
GregorianCalendar gc =new GregorianCalendar();
SimpleDateFormat sf  =new SimpleDateFormat("yyyy-MM-dd");

public String getYears()
{
gc.setTime(d);
gc.add(1,+1);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

return sf.format(gc.getTime());
}

public String getHalfYear()
{
gc.setTime(d);
gc.add(2,+6);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

return sf.format(gc.getTime());
}
public String getQuarters()
{
gc.setTime(d);
gc.add(2,+3);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

return sf.format(gc.getTime());
}

public String getLocalDate()
{
return sf.format(d);
}


public static  void  main(String[] args)
{
UseDate ud= new UseDate();
System.out.println(ud.getLocalDate());
System.out.println(ud.getYears());
System.out.println(ud.getHalfYear());
System.out.println(ud.getQuarters());
}

}



4 ,

GregorianCalendar gc=new GregorianCalendar();
        
        try {
            gc.setTime( new SimpleDateFormat("yyyyMM").parse("200901"));
            gc.add(2, -Integer.parseInt("7"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(new SimpleDateFormat("yyyyMM").format(gc.getTime()));

運転結果:200806