取得当前日期的比较
来源:互联网 发布:基金知乎 编辑:程序博客网 时间: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更方便,所以在开发中使用前者比较多。。。。。。。。。
- 取得当前日期的比较
- JS取得当前日期的农历
- PHP进阶篇:取得当前的日期
- 取得当前日期
- javascript 取得当前日期
- 当前日期和设定日期的比较
- 当前日期与制定日期的比较
- Web页面取得当前日期
- 根据当前时间取得星期一跟星期天的日期
- MySQL取得当前日期固定时间的方法。
- JAVA 取得当前日期的前一天,后一天
- SQL取得当前日期及日期格式
- 比较两个日期的大小和或得当前日期
- 取得当前日期 date()函数详解
- flex中取得当前时间日期
- 取得日期的星期
- 比较两个日期的大小 NSDate获取当前日期 进行比较
- 固定日期与当前系统时间的比较 (QDate)
- 1-2 Windows下启动函数(真正的入口函数) 之 寻找入口函数与_security_init_cookie
- struct linger 用法
- 啥发V大规范和那个年纪
- 稀释剂影响汽车低温烤漆
- cuda编程:关于共享内存(shared memory)和存储体(bank)的事实和疑惑
- 取得当前日期的比较
- 行不啊
- 设计模式大总结(一)
- 语言集成查询(LINQ)
- 男子杀友获对方父亲谅解 法庭上连磕8个头
- 房间里的大象
- 开发那朵花
- Your Ride Is Here 你的飞碟在这儿
- 黑马程序员—交通灯管理系统梳理