首页 > 代码库 > DateUtil工具类

DateUtil工具类

package com.workit.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil{

public static final String DATE_DEFAULT_FORMAT="yyyy-MM-dd HH:mm:ss";

public static final String DATE_DAY_SPE_FORMAT="yyyy-MM-dd";

public static final String DATE_DATETIME_FORMAT="yyyyMMddHHmmss";

public static final String DATE_TIME_FORMAT="HH:mm:ss";

public static final String DATE_MON_FORMAT="yyyyMM";


/**
* @see 日期转字符串
* @param date
* @param format:时间格式
* @return dateStr:时间字符串
* @author XiaBingCheng
* @date 2017-07-24
*/
public static String DateToString(Date date){
SimpleDateFormat sdf = new SimpleDateFormat(DATE_DEFAULT_FORMAT);
String dateStr = sdf.format(date);
System.out.println(dateStr);
return dateStr;
}

/**
* @see 字符串转日期
* @param str
* @param format:时间格式
* @return date
* @author XiaBingCheng
* @date 2017-07-24
*/
public static Date StringToDate(String str){
SimpleDateFormat sdf = new SimpleDateFormat(DATE_DEFAULT_FORMAT);
Date date = new Date();
try {
date = sdf.parse(str);
System.out.println(date.toLocaleString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}

/**
* @see获取昨天的时间
* @param format:时间格式
* @return sdf.format(calendar.getTime())
* @author XiaBingCheng
* @date 2017-07-24
*/
public static String GetYesterDay(){
SimpleDateFormat sdf = new SimpleDateFormat(DATE_DAY_SPE_FORMAT);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
System.out.println(sdf.format(calendar.getTime()));
return sdf.format(calendar.getTime());
}

/**
* @see 获取上个月的时间
* @param format:时间格式
* @return sdf.format(calendar.getTime())
* @author XiaBingCheng
* @date 2017-07-24
*/
public static String GetLastMonthDay(){
SimpleDateFormat sdf = new SimpleDateFormat(DATE_DAY_SPE_FORMAT);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
System.out.println(sdf.format(calendar.getTime()));
return sdf.format(calendar.getTime());
}

/**
* @see 计算两个日期之间相差的月数(暂时不写)
* @param date1
* @param date2
* @return int
* @author XiaBingCheng
* @date 2017-07-24
*/
public static int getCountBetweenDates(Date date1,Date date2){
int mouthCount = 0;
int flag = 0;
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
if(calendar2.equals(calendar1)){
return 0;
}
return 0;
}

}

DateUtil工具类