Java對日期操做處理類
項目中常常用到對日期相關操做 java
package com.seg.common.util;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 日期處理工具類
* @author Lee
*/
public class DateUtil {
//~ Static fields/initializers =============================================
private static Log log = LogFactory.getLog(DateUtil.class);
private static String defaultDatePattern = null;
private static String timePattern = "HH:mm" ;
public static final String TS_FORMAT = DateUtil.getDatePattern() + " HH:mm:ss.S" ;
private static Calendar cale = Calendar.getInstance();
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd" );
private static SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss" );
private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
//~ Methods ================================================================
public DateUtil(){
}
/**
* 得到服務器當前日期及時間,以格式爲:yyyy-MM-dd HH:mm:ss的日期字符串形式返回
*/
public static String getDateTime(){
try{
return sdf2.format(cale.getTime());
} catch(Exception e){
log.debug("DateUtil.getDateTime():" + e.getMessage());
return "" ;
}
}
/**
* 得到服務器當前日期,以格式爲:yyyy-MM-dd的日期字符串形式返回
*/
public static String getDate(){
try{
return sdf.format(cale.getTime());
} catch(Exception e){
log.debug("DateUtil.getDate():" + e.getMessage());
return "" ;
}
}
/**
* 得到服務器當前時間,以格式爲:HH:mm:ss的日期字符串形式返回
*/
public static String getTime(){
String temp = "" ;
try{
temp += sdf1.format(cale.getTime());
return temp;
} catch(Exception e){
log.debug("DateUtil.getTime():" + e.getMessage());
return "" ;
}
}
/**
* 統計時開始日期的默認值,
* 今年的開始時間
*/
public static String getStartDate(){
try{
return getYear() + "-01-01" ;
} catch(Exception e){
log.debug("DateUtil.getStartDate():" + e.getMessage());
return "" ;
}
}
/**
* 統計時結束日期的默認值
*/
public static String getEndDate(){
try{
return getDate();
} catch(Exception e){
log.debug("DateUtil.getEndDate():" + e.getMessage());
return "" ;
}
}
/**
* 得到服務器當前日期的年份
*/
public static String getYear(){
try{
//返回的int型,須要字符串轉換
return String.valueOf(cale.get(Calendar.YEAR));
} catch(Exception e){
log.debug("DateUtil.getYear():" + e.getMessage());
return "" ;
}
}
/**
* 得到服務器當前日期的月份
*/
public static String getMonth(){
try{
//一個數字格式,很是好
java.text.DecimalFormat df = new java.text.DecimalFormat();
df.applyPattern("00" );
return df.format((cale.get(Calendar.MONTH) + 1 ));
//return String.valueOf(cale.get(Calendar.MONTH) + 1 );
} catch(Exception e){
log.debug("DateUtil.getMonth():" + e.getMessage());
return "" ;
}
}
/**
* 得到服務器在當前月中天數
*/
public static String getDay(){
try{
return String.valueOf(cale.get(Calendar.DAY_OF_MONTH));
} catch(Exception e){
log.debug("DateUtil.getDay():" + e.getMessage());
return "" ;
}
}
/**
* 比較兩個日期相差的天數,
* 第一個日期要比第二個日期要晚
*/
public static int getMargin(String date1,String date2){
int margin;
try{
ParsePosition pos = new ParsePosition(0 );
ParsePosition pos1 = new ParsePosition(0 );
Date dt1 = sdf.parse(date1,pos);
Date dt2 = sdf.parse(date2,pos1);
long l = dt1.getTime() - dt2.getTime();
margin = (int)(l / (24 * 60 * 60 * 1000 ));
return margin;
} catch(Exception e){
log.debug("DateUtil.getMargin():" + e.toString());
return 0 ;
}
}
/**
* 比較兩個日期相差的天數,格式不同
* 第一個日期要比第二個日期要晚
*/
public static double getDoubleMargin(String date1,String date2){
double margin;
try{
ParsePosition pos = new ParsePosition(0 );
ParsePosition pos1 = new ParsePosition(0 );
Date dt1 = sdf2.parse(date1,pos);
Date dt2 = sdf2.parse(date2,pos1);
long l = dt1.getTime() - dt2.getTime();
margin = (l / (24 * 60 * 60 * 1000.00 ));
return margin;
} catch(Exception e){
log.debug("DateUtil.getMargin():" + e.toString());
return 0 ;
}
}
/**
* 比較兩個日期相差的月數
*/
public static int getMonthMargin(String date1,String date2){
int margin;
try{
margin = (Integer.parseInt(date2.substring(0 , 4 )) - Integer.parseInt(date1.substring( 0 , 4 )))* 12 ;
margin += (Integer.parseInt(date2.substring(4 , 7 ).replaceAll( "-0" , "-" )) - Integer.parseInt(date1.substring( 4 , 7 ).replaceAll( "-0" , "-" )));
return margin;
} catch(Exception e){
log.debug("DateUtil.getMargin():" + e.toString());
return 0 ;
}
}
/**
* 返回日期加X天后的日期
*/
public static String addDay(String date,int i){
try{
GregorianCalendar gCal = new GregorianCalendar(Integer.parseInt(date.substring(0 , 4 )),Integer.parseInt(date.substring( 5 , 7 ))- 1 ,Integer.parseInt(date.substring( 8 , 10 )));
gCal.add(GregorianCalendar.DATE,i);
return sdf.format(gCal.getTime());
} catch(Exception e){
log.debug("DateUtil.addDay():" + e.toString());
return getDate();
}
}
/**
* 返回日期加X月後的日期
*/
public static String addMonth(String date,int i){
try{
GregorianCalendar gCal = new GregorianCalendar(Integer.parseInt(date.substring(0 , 4 )),Integer.parseInt(date.substring( 5 , 7 ))- 1 ,Integer.parseInt(date.substring( 8 , 10 )));
gCal.add(GregorianCalendar.MONTH,i);
return sdf.format(gCal.getTime());
} catch(Exception e){
log.debug("DateUtil.addMonth():" + e.toString());
return getDate();
}
}
/**
* 返回日期加X年後的日期
*/
public static String addYear(String date,int i){
try{
GregorianCalendar gCal = new GregorianCalendar(Integer.parseInt(date.substring(0 , 4 )),Integer.parseInt(date.substring( 5 , 7 ))- 1 ,Integer.parseInt(date.substring( 8 , 10 )));
gCal.add(GregorianCalendar.YEAR,i);
return sdf.format(gCal.getTime());
} catch(Exception e){
log.debug("DateUtil.addYear():" + e.toString());
return "" ;
}
}
/**
* 返回某年某月中的最大天
*/
public static int getMaxDay(String year,String month){
int day = 0 ;
try{
int iyear = Integer.parseInt(year);
int imonth = Integer.parseInt(month);
if(imonth == 1 || imonth == 3 || imonth == 5 || imonth == 7 || imonth == 8 || imonth == 10 || imonth == 12 ){
day = 31 ;
} else if(imonth == 4 || imonth == 6 || imonth == 9 || imonth == 11 ){
day = 30 ;
} else if((0 == (iyear % 4 )) && ( 0 != (iyear % 100 )) || ( 0 == (iyear % 400 ))){
day = 29 ;
} else{
day = 28 ;
}
return day;
} catch(Exception e){
log.debug("DateUtil.getMonthDay():" + e.toString());
return 1 ;
}
}
/**
* 格式化日期
*/
@SuppressWarnings("static-access" )
public String rollDate(String orgDate,int Type,int Span){
try{
String temp = "" ;
int iyear,imonth,iday;
int iPos = 0 ;
char seperater = '-' ;
if(orgDate == null || orgDate.length() < 6 ){
return "" ;
}
iPos = orgDate.indexOf(seperater);
if(iPos > 0 ){
iyear = Integer.parseInt(orgDate.substring(0 ,iPos));
temp = orgDate.substring(iPos + 1 );
} else{
iyear = Integer.parseInt(orgDate.substring(0 , 4 ));
temp = orgDate.substring(4 );
}
iPos = temp.indexOf(seperater);
if(iPos > 0 ){
imonth = Integer.parseInt(temp.substring(0 ,iPos));
temp = temp.substring(iPos + 1 );
} else{
imonth = Integer.parseInt(temp.substring(0 , 2 ));
temp = temp.substring(2 );
}
imonth--;
if(imonth < 0 || imonth > 11 ){
imonth = 0 ;
}
iday = Integer.parseInt(temp);
if(iday < 1 || iday > 31 )
iday = 1 ;
Calendar orgcale = Calendar.getInstance();
orgcale.set(iyear,imonth,iday);
temp = this.rollDate(orgcale,Type,Span);
return temp;
}catch(Exception e){
return "" ;
}
}
public static String rollDate(Calendar cal,int Type,int Span){
try{
String temp = "" ;
Calendar rolcale;
rolcale = cal;
rolcale.add(Type,Span);
temp = sdf.format(rolcale.getTime());
return temp;
}catch(Exception e){
return "" ;
}
}
/**
*
* 返回默認的日期格式
*
*/
public static synchronized String getDatePattern() {
defaultDatePattern = "yyyy-MM-dd" ;
return defaultDatePattern;
}
/**
* 將指定日期按默認格式進行格式代化成字符串後輸出如:yyyy-MM-dd
*/
public static final String getDate(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "" ;
if (aDate != null) {
df = new SimpleDateFormat(getDatePattern());
returnValue = df.format(aDate);
}
return (returnValue);
}
/**
* 取得給定日期的時間字符串,格式爲當前默認時間格式
*/
public static String getTimeNow(Date theTime) {
return getDateTime(timePattern, theTime);
}
/**
* 取得當前時間的Calendar日曆對象
*/
public Calendar getToday() throws ParseException {
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat(getDatePattern());
String todayAsString = df.format(today);
Calendar cal = new GregorianCalendar();
cal.setTime(convertStringToDate(todayAsString));
return cal;
}
/**
* 將日期類轉換成指定格式的字符串形式
*/
public static final String getDateTime(String aMask, Date aDate) {
SimpleDateFormat df = null;
String returnValue = "" ;
if (aDate == null) {
log.error("aDate is null!" );
} else {
df = new SimpleDateFormat(aMask);
returnValue = df.format(aDate);
}
return (returnValue);
}
/**
* 將指定的日期轉換成默認格式的字符串形式
*/
public static final String convertDateToString(Date aDate) {
return getDateTime(getDatePattern(), aDate);
}
/**
* 將日期字符串按指定格式轉換成日期類型
* @param aMask 指定的日期格式,如:yyyy-MM-dd
* @param strDate 待轉換的日期字符串
*/
public static final Date convertStringToDate(String aMask, String strDate)
throws ParseException {
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(aMask);
if (log.isDebugEnabled()) {
log.debug("converting '" + strDate + "' to date with mask '"
+ aMask + "'" );
}
try {
date = df.parse(strDate);
} catch (ParseException pe) {
log.error("ParseException: " + pe);
throw pe;
}
return (date);
}
/**
* 將日期字符串按默認格式轉換成日期類型
*/
public static Date convertStringToDate(String strDate)
throws ParseException {
Date aDate = null;
try {
if (log.isDebugEnabled()) {
log.debug("converting date with pattern: " + getDatePattern());
}
aDate = convertStringToDate(getDatePattern(), strDate);
} catch (ParseException pe) {
log.error("Could not convert '" + strDate
+ "' to a date, throwing exception" );
throw new ParseException(pe.getMessage(),
pe.getErrorOffset());
}
return aDate;
}
/**
* 返回一個JAVA簡單類型的日期字符串
*/
public static String getSimpleDateFormat(){
SimpleDateFormat formatter=new SimpleDateFormat();
String NDateTime=formatter.format(new Date());
return NDateTime;
}
/**
* 將兩個字符串格式的日期進行比較
* @param last 要比較的第一個日期字符串
* @param now 要比較的第二個日期格式字符串
* @return true(last 在now 日期以前),false(last 在now 日期以後)
*/
public static boolean compareTo(String last, String now) {
try {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss" );
Date temp1 = formatter.parse(last);
Date temp2 = formatter.parse(now);
if (temp1.after(temp2))
return false;
else if (temp1.before(temp2))
return true;
} catch (ParseException e) {
log.debug(e.getMessage());
}
return false;
}
protected Object convertToDate(Class type, Object value) {
DateFormat df = new SimpleDateFormat(TS_FORMAT);
if (value instanceof String) {
try {
if (StringUtils.isEmpty(value.toString())) {
return null;
}
return df.parse((String) value);
} catch (Exception pe) {
throw new ConversionException("Error converting String to Timestamp" );
}
}
throw new ConversionException("Could not convert "
+ value.getClass().getName() + " to " + type.getName());
}
/**
* 爲查詢日期添加最小時間
* @param 目標類型Date
* @param 轉換參數Date
* @return
*/
@SuppressWarnings("deprecation" )
public static Date addStartTime(Date param) {
Date date = param;
try{
date.setHours(0 );
date.setMinutes(0 );
date.setSeconds(0 );
return date;
}catch(Exception ex){
return date;
}
}
/**
* 爲查詢日期添加最大時間
* @param 目標類型Date
* @param 轉換參數Date
* @return
*/
@SuppressWarnings("deprecation" )
public static Date addEndTime(Date param) {
Date date = param;
try{
date.setHours(23 );
date.setMinutes(59 );
date.setSeconds(0 );
return date;
}catch(Exception ex){
return date;
}
}
/**
* 返回系統如今年份中指定月份的天數
* @param 月份month
* @return 指定月的總天數
*/
@SuppressWarnings("deprecation" )
public static String getMonthLastDay(int month)
{
Date date=new Date();
int[][] day={{0 , 30 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 },
{0 , 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 }};
int year=date.getYear()+1900 ;
if(year%4 == 0 && year% 100 != 0 || year% 400 == 0 )
{
return day[1 ][month]+ "" ;
}
else
{
return day[0 ][month]+ "" ;
}
}
/**
* 返回指定年份中指定月份的天數
* @param 年份year
* @param 月份month
* @return 指定月的總天數
*/
public static String getMonthLastDay(int year,int month)
{
int[][] day={{0 , 30 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 },
{0 , 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 }};
if(year%4 == 0 && year% 100 != 0 || year% 400 == 0 )
{
return day[1 ][month]+ "" ;
}
else
{
return day[0 ][month]+ "" ;
}
}
/**
* 取得當前時間的日戳
* @return
*/
@SuppressWarnings("deprecation" )
public static String getTimestamp(){
Date date=new Date();
String timestamp="" +(date.getYear()+ 1900 )+date.getMonth()+date.getDate()+date.getMinutes()+date.getSeconds()+date.getTime();
return timestamp;
}
/**
* 取得指定時間的日戳
* @return
*/
@SuppressWarnings("deprecation" )
public static String getTimestamp(Date date){
String timestamp="" +(date.getYear()+ 1900 )+date.getMonth()+date.getDate()+date.getMinutes()+date.getSeconds()+date.getTime();
return timestamp;
}
public static void main(String[] args){
System.out.println(DateUtil.getDate());//獲取日期格式爲2010 - 08 - 12
System.out.println(DateUtil.getDateTime());//獲取日期格式爲2010 - 08 - 12 18 : 08 : 21
System.out.println(DateUtil.getTime());//獲取日期格式爲18 : 08 : 21
System.out.println(DateUtil.getYear());//獲取當前時間年份2010
System.out.println(DateUtil.getMonth());//獲取當年時間月份08
System.out.println(DateUtil.getStartDate());//獲取2010 - 01 - 01
System.out.println(DateUtil.getEndDate());//2010 - 08 - 12
System.out.println(DateUtil.getDay());//得到服務器在當前月中已通過了的天數12
System.out.println(DateUtil.getMargin("2010-05-02" , "2010-04-01" ));//比較兩個日期相差的天數
System.out.println(DateUtil.getDoubleMargin("2010-05-07 23:22:11" , "2010-04-01 01:33:33" ));
}
}
歡迎關注本站公眾號,獲取更多信息