取得当前日期的比较

来源:互联网 发布:基金知乎 编辑:程序博客网 时间:2024/04/30 03:56

加强Dete  StringBuffer SimpleDateFormat Calendar类的联系

在开发中经常要取得日期,而且每次取得日期的代码都会重复,所以重复的代码就可以定义成一个类,以方便重复调用。。。

import java.util.* ; // 导入需要的工具包
class DateTime{ // 以后直接通过此类就可以取得日期时间
private Calendar calendar = null ;// 声明一个Calendar对象,取得时间
public DateTime(){// 构造方法中直接实例化对象
this.calendar = new GregorianCalendar() ;
}
public String getDate(){// 得到的是一个日期:格式为:yyyy-MM-dd HH:mm:ss.SSS
// 考虑到程序要频繁修改字符串,所以使用StringBuffer提升性能
StringBuffer buf = new StringBuffer() ;
buf.append(calendar.get(Calendar.YEAR)).append("-") ;// 增加年
buf.append(this.addZero(calendar.get(Calendar.MONTH)+1,2)).append("-") ;// 增加月
buf.append(this.addZero(calendar.get(Calendar.DAY_OF_MONTH),2)).append(" ") ;// 取得日
buf.append(this.addZero(calendar.get(Calendar.HOUR_OF_DAY),2)).append(":") ;// 取得时
buf.append(this.addZero(calendar.get(Calendar.MINUTE),2)).append(":") ;
buf.append(this.addZero(calendar.get(Calendar.SECOND),2)).append(".") ;
buf.append(this.addZero(calendar.get(Calendar.MILLISECOND),3)) ;
return buf.toString() ;
}

// 考虑到日期中存在前导0,所以在此处加上补零的方法
private String addZero(int num,int len){
StringBuffer s = new StringBuffer() ;
s.append(num) ;
while(s.length()<len){// 如果长度不足,则继续补0
s.insert(0,"0") ;// 在第一个位置处补0
}
return s.toString() ;
}
};
public class DateDemo06{
public static void main(String args[]){
DateTime dt = new DateTime() ;
System.out.println("系统日期:"+dt.getDate()) ;
}
};

基于SimpleDateFormat

此类中存在一个方法,可以对Date重新格式化

如果将一个表示日期的Date通过制定的模板进行相关的操作,那么就很方便了

import java.text.* ;
import java.util.* ;// 导入需要的工具包
class DateTime{ // 以后直接通过此类就可以取得日期时间
private SimpleDateFormat sdf=null;
public String getDate(){
this.sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // 得到的是一个日期:格式为:yyyy-MM-dd HH:mm:ss.SSS


return this.sdf.format(new Date()) ;
}

};
public class DateDemo07{
public static void main(String args[]){
DateTime dt = new DateTime() ;
System.out.println("系统日期:"+dt.getDate()) ;
}
};

从以上代码可以看出,在开发中使用SimpleDateFormat比 Canlendar更方便,所以在开发中使用前者比较多。。。。。。。。。

0 0