日期计算与格式化

import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class DateUtil {

public static final int SECONDE=1000;
public static final int MINUTE=SECONDE* 60;
public static final int HOUR=MINUTE * 60;
public static final int DAY=HOUR * 24;

public final static String DATE_FORMATE = "MM/dd/yyyy";
public final static String DATETIME_FORMATE = DATE_FORMATE + " HH:mm";

private static Calendar c=Calendar.getInstance();

private DateUtil(){
//nothing
}

public static Date buildDate(int year,int month,int day){
c.set(Calendar.YEAR,year);
c.set(Calendar.MONTH,month);
c.set(Calendar.DAY_OF_MONTH,day);
c.set(Calendar.HOUR,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
return c.getTime();
}

public static Date buildDate(int month,int day){
c.set(Calendar.MONTH,month);
c.set(Calendar.DAY_OF_MONTH,day);
c.set(Calendar.HOUR,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
return c.getTime();
}
//给定日期(date)与天数(day),计算出从date开始day天后的日期
public static Date afterDays(Date someday,int days){
c.setTimeInMillis(someday.getTime()+DAY*days);
return c.getTime();
}

public static Date beforeDays(Date someday,int days){
return afterDays(someday,-days);
}
//明天
public static Date tomorrow(){
return afterDays(new Date(),1);
}
//昨天
public static Date yestoday(){
return beforeDays(new Date(),1);
}

public static Date parseDate(String str,String format,Date defaultValue) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date result;
try {
result=sdf.parse(str);
} catch (ParseException e) {
return defaultValue;
} catch (IllegalArgumentException iae) {
return defaultValue;
}

return result;
}

public static Date parseDate(String str,Date defaultValue) {
return parseDate(str, DATETIME_FORMATE,defaultValue);
}
//解析日期
public static Date parseDate(String str,String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(str);
}

public static Date parseDate(String str) throws ParseException {
return parseDate(str,DATETIME_FORMATE);
}
//格式化日期格式
public static String format(Date d,String format){
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(d);
}

public static String format(Date d){
return format(d,DATETIME_FORMATE);
}

public static String format(String format){
return format(new Date(),format);
}

public static String format(){
return format(new Date());
}

public static void main(String[] args) {
System.out.println(DateUtil.buildDate(2007,5,16));
System.out.println(DateUtil.buildDate(5,16));
System.out.println(DateUtil.tomorrow());
System.out.println(DateUtil.yestoday());
System.out.println(DateUtil.format());
}


}

得安奇专卖(运动休闲鞋,板鞋):www.bxbshoes.com

你可能感兴趣的:(C++,c,C#)