在java中處理日期我覺得不方便,需要引入好幾個包Date和SimpleDateFormat或者DateFormat,而且Date設定日期我覺得很不方便,為了方便操作Date我寫了一個類名為FlexDate,在類裡處理日期、擷取日期,我是覺得寫一個類很方便,下面是代碼,如果覺得哪裡寫的不好還請朋友們多多指教。
package org.fengdong;
import java.text.SimpleDateFormat;
import java.util.Date;
/** *//**
* Created by IntelliJ IDEA.
* ClassName:日期擴充類
* User: 馮東
* Date: 2007-9-9
* Time: 10:28:55
* To change this template use File | Settings | File Templates.
*/
public class FlexDate extends Date {
private SimpleDateFormat simpleDateFormat;
private Date date;
public FlexDate() {
this(new Date());
}
public FlexDate(Date date) {
this(date, "yyyy-MM-dd");
}
public FlexDate(Date date, String formatPattern) {
this.simpleDateFormat = new SimpleDateFormat(formatPattern);
this.date = new Date();
try {
this.date = this.simpleDateFormat.parse(this.simpleDateFormat.format(date));
}
catch (Exception exp) {
exp.printStackTrace();
}
}
/**//* public FlexDate(String dateString) {
String splitString = dateString.substring(3,4);
String formatPatten = "";
System.out.println(splitString);
if(splitString.equals("/") || splitString.equals("-"))
{
formatPatten = "yyyy" + splitString + "MM" + splitString + "dd";
}
else
{
formatPatten = "yyyyMMdd";
}
this(dateString, formatPatten);
}*/
/**//*
* 根據日期格式字串和格式化字串初始化
* */
public FlexDate(String dateString, String formatPattern) {
this.simpleDateFormat = new SimpleDateFormat(formatPattern);
date = new Date();
try {
date = this.simpleDateFormat.parse(dateString);
}
catch (Exception exp) {
exp.printStackTrace();
}
}
/**//*
* 擷取日期格式化字串
* */
public String getFormatePattern() {
return this.simpleDateFormat.toPattern();
}
/**//*
* 設定格日期格式化字串
* */
public void setFormatePattern(String formatString) {
this.simpleDateFormat.applyPattern(formatString);
}
/**//*
*設定日期格式的字串
* @para dateString
* 注意:此字串的格式必須與設定的FormatPatten一致
*/
public void setDateString(String dateString) {
try {
this.date = this.simpleDateFormat.parse(dateString);
}
catch (Exception exp) {
exp.printStackTrace();
}
}
/**//*
* 返回當前設定日期的字串格式
* */
public String getDateString()
{
return this.simpleDateFormat.format(this.date);
}
/**//*
* 擷取設定的時間對象
* */
public Date getFlexDate() {
return date;
}
/**//*
* 設定時間對象
* */
public void setDate(Date date) {
this.date = date;
}
/**//*
* 返回日期文字
* */
public String toString()
{
return getDateString();
}
}