您的位置:首页 > 编程语言 > Java开发

java中的时间计算和格式处理方法

2013-05-17 10:49 525 查看
//一天秒数

public final static long MILLISECONDS_OF_DAY = 1000 * 60 * 60 * 24;

public final static long MINUTES_OF_DAY = 1000 * 60 * 60 * 24;

public final static int days[] = {31,29,31,30,31,30,31,31,30,31,30,31};

public final static int WEEK_LENGTH=7;

public final static int YEAR_LENGTH=12;

public final static int NULL_DATE = 19000101;

public final static String NULLDATE="1900-01-01";

public final static int DATETIME_LENGTH = 14;

public final static int DATE_LENGTH = 8;

public final static int TIME_LENGTH = 6;

/**

* 将YYYY-MM-DD HH:NN:SS类型的字符串转化为Date类型

* @param date

* @return Date类型

* @throws ParseException

*/

public static Date parse(String date) throws ParseException {

boolean isDate = date.indexOf('-') > 0;

boolean isTime = date.indexOf(':') > 0;

if (isDate && isTime) { //日期时间

SimpleDateFormat dateTimeF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

return dateTimeF.parse(date);

} else if (isDate) {

SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd");

return dateF.parse(date);

} else if (isTime) {

SimpleDateFormat timeF = new SimpleDateFormat("HH:mm:ss");

return timeF.parse(date);

}

return new Date(0);

}

/**

* 将YYYY-MM-DD HH:NN:SS.SSS类型的字符串转化为Date类型

* @param date

* @return Date类型

* @throws ParseException

*/

public static Date parseMinSec(String date) throws ParseException {

boolean isDate = date.indexOf('-') > 0;

boolean isTime = date.indexOf(':') > 0;

if (isDate && isTime) { //日期时间

SimpleDateFormat dateTimeF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

return dateTimeF.parse(date);

} else if (isDate) {

SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd");

return dateF.parse(date);

} else if (isTime) {

SimpleDateFormat timeF = new SimpleDateFormat("HH:mm:ss.SSS");

return timeF.parse(date);

}

return new Date(0);

}

/**

* 转化为整型

* @param dateTime

* @return 整型的日期值

* @throws ParseException

*/

public static int toInteger(String dateTime)throws ParseException {

Calendar cal = Calendar.getInstance();

cal.setTime(parse(dateTime));

return cal.get(Calendar.YEAR) * 10000

+ (cal.get(Calendar.MONTH)+1) * 100

+ cal.get(Calendar.DAY_OF_MONTH);

}

public static String mulFreq(String freq, int muls){

int num = Integer.parseInt(freq.substring(0, freq.length() - 1));

return Integer.toString(num) + freq.substring(freq.length() - 1, 1);

}

public static int toInteger(Date dateTime) {

Calendar cal = Calendar.getInstance();

cal.setTime(dateTime);

return cal.get(Calendar.YEAR) * 10000

+ (cal.get(Calendar.MONTH)+1) * 100

+ cal.get(Calendar.DAY_OF_MONTH);

}

/**

* 返回某一频率下的两个日期间的次数

* @param start

* @param end

* @param freq

* @return int 次数

* @throws ParseException

*/

public static int indexOf(String start, String end, String freq) throws ParseException{

Date date1 = GenernalDate.parse(start);

Date date2 = GenernalDate.parse(end);

for(int i = 0;;i++) {

if( date1.getTime() >= date2.getTime() ) {

return i;

}

date1 = GenernalDate.add(date1, freq);

}

}

/**

* 返回两个日期相差年数

* @param start

* @param end

* @return 相差年数

* @throws ParseException

*/

public static int yearsOf(String start, String end)throws ParseException{

Calendar cal1 = Calendar.getInstance();

cal1.setTime(parse(start));

Calendar cal2 = Calendar.getInstance();

cal2.setTime(parse(end));

return cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR) + 1;

}

/**

* 从日期时间字符串拆出日期

* @param dateTime

* @return 日期

* @throws ParseException

*/

public static String splitDate(String dateTime) throws ParseException {

return formatDate(parse(dateTime));

}

/**

* 从日期时间字符串拆出时间

* @param dateTime

* @return 时间

* @throws ParseException

*/

public static String splitTime(String dateTime) throws ParseException {

return formatTime(parse(dateTime));

}

/**

* 返回日期

* @param date

* @return Date

* @throws ParseException

*/

public static Date parseDate(String date) throws ParseException {

SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd");

return dateF.parse(date);

}

public static Calendar parseCalendar(String date){

Calendar cal = Calendar.getInstance();

SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd");

try{

cal.setTime(dateF.parse(date));

}catch(ParseException e){

throw new RuntimeException(e);

}

return cal;

}

/**

* 返回时间

* @param time

* @return Date 时间

* @throws ParseException

*/

public static Date parseTime(String time) throws ParseException {

SimpleDateFormat timeF = new SimpleDateFormat("HH:mm:ss");

return timeF.parse(time);

}

/**

* 两个日期相减,参数为String型

* @param startDate

* @param endDate

* @return int

*/

public static int offset(String startDate, String endDate) throws ParseException {

return offset(parse(startDate), parse(endDate));

}

/**

* 两个日期相减,参数为Date型

* @param startDate

* @param endDate

* @return int 日期差

*/

public static int offset(Date startDate, Date endDate) {

return (int) ((endDate.getTime() - startDate.getTime()) / MINUTES_OF_DAY);

}

/**

* 两个日期相减,参数为Date型

* @param startDate

* @param endDate

* @return int 日期差

*/

public static int offsetDay(Date startDate, Date endDate)throws ParseException {

return offset(parse(formatDate(startDate)),parse(formatDate(endDate)));

}

/**

* 日期加天数

* @return 日期加天数后的Date日期

*/

public static Date addDays(Date date, int days) {

return new Date(date.getTime() + days * MINUTES_OF_DAY);

}

/**

* 日期加天数

* @param date

* @param days

* @return 日期加天数后的String日期

*/

public static String addDays(String date, int days) throws ParseException {

return formatDate(addDays(parse(date), days));

}

/**

* +月

* @param date 起始日期

* @param months 月数

* @return 日期加月数后的Date日期

* @throws ParseException

*/

public static Date addMonths(Date date, int months) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.add(Calendar.MONTH, months);

return cal.getTime();

}

/**

* +月

* @param date 起始日期

* @param months 月数

* @return 日期加月数后的String日期

* @throws ParseException

*/

public static String addMonths(String date, int months) throws ParseException {

return formatDate(addMonths(parseDate(date), months));

}

/**

* +年

* @param date 起始日期

* @param years 年数

* @return 日期加年数后的Date日期

* @throws ParseException

*/

public static Date addYears(Date date, int years) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.add(Calendar.YEAR, years);

return cal.getTime();

}

/**

* +年

* @param date 起始日期

* @param years 年数

* @return 日期加年数后的String日期

* @throws ParseException

*/

public static String addYears(String date, int years) throws ParseException {

return formatDate(addYears(parseDate(date), years));

}

/**

* +秒

* @param date 起始日期

* @param second 秒

* @return 日期加秒数后的Date日期

* @throws ParseException

*/

public static Date addSecond(Date date, int second) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.add(Calendar.SECOND, second);

return cal.getTime();

}

public static Date addHour(Date date, int hours) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.add(Calendar.HOUR, hours);

return cal.getTime();

}

public static Date addMinutes(Date date, int minutes) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

cal.add(Calendar.MINUTE, minutes);

return cal.getTime();

}

/**

* + 表达式 d,w,m,y

* @param date 起始日期

* @param exp 表达式类型:d/D 天; w/W 周; m/M 月; y/Y 年

* @param mul 乘数,一般是第mul期,如exp:7d,mul:2,则为加7*2d

* @param monthEnd 月末是否对齐

* @return 计算后的Date日期

* @throws ParseException

* @throws NumberFormatException

*/

public static Date add(Date date,String exp, int mul, boolean monthEnd){

if( exp.length() <= 1 ) {

throw new RuntimeException("payFreq is null!");

}

int len = exp.length();

int num = Integer.parseInt(exp.substring(0, len - 1)) * mul;

Date ndate = null;

switch (exp.charAt(len - 1)) {

case 'd':

case 'D':

return addDays(date, num);

case 'w':

case 'W':

return addDays(date, num * 7);

case 'm':

case 'M':

ndate = addMonths(date, num);

break;

case 'y':

case 'Y':

ndate = addYears(date, num);

break;

}

if( monthEnd && ndate != null ) {//&& isMonthEnd(date)

return getMonthEnd(ndate);

} else {

return ndate;

}

}

/**

*

* @param date

* @param j

* @return Date

*/

public static Date rollMonth(Date date ,int j){

Date tmp = addMonths(date, j - 1);

return getMonthEnd(tmp);

}

/**

* 是否月末

* @param date

* @return boolean 是否月末

*/

public static boolean isMonthEnd(Date date) {

GregorianCalendar cal = new GregorianCalendar();

cal.setTime(date);

if( cal.get(GregorianCalendar.DAY_OF_MONTH) ==

cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH)){

return true;

}

return false;

}

/**

* 返回日期的月末时间

* @param date

* @return Date

*/

public static Date getMonthEnd(Date date) {

GregorianCalendar cal = new GregorianCalendar();

cal.setTime(date);

cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH));

return cal.getTime();

}

/**

* 返回日期的月初时间

* @param date

* @return Date

*/

public static Date getMonthStart(Date date) {

GregorianCalendar cal = new GregorianCalendar();

cal.setTime(date);

cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(GregorianCalendar.DAY_OF_MONTH));

return cal.getTime();

}

/**

* 比较表达式的大小

* @param exp1

* @param exp2

* @return 表达式(折算成天)相减后的值

*/

public static int compare(String exp1, String exp2){

return getDays(exp1) - getDays(exp2);

}

private static int getDays(String exp) {

int len = exp.length();

int num = Integer.parseInt(exp.substring(0, len - 1));

int days = 0;

char c = exp.charAt(len - 1);

if( c == 'd' || c == 'D'){

days = num;

} else if( c == 'w' || c == 'W'){

days = num * 7;

}else if( c == 'm' || c == 'M'){

days = num * 30;

}else if( c == 'y' || c == 'Y'){

days = num * 365;

}

return days;

}

public static Date add(Date date, String exp) {

return add(date,exp,1, false);

}

/**

* +表达式,d,w,m,y

* @param date

* @param exp

* @return String类型的日期

* @throws ParseException

*/

public static String add(String date, String exp) throws ParseException {

return formatDate(add(parseDate(date), exp));

}

/**

* 日期+时间

* @param date

* @param time

* @return 包含日期、时间的Date日期

*/

public static Date add(Date date, Date time) {

Calendar cal0 = Calendar.getInstance();

Calendar cal1 = Calendar.getInstance();

cal0.setTime(date);

cal1.setTime(time);

cal0.set(Calendar.HOUR_OF_DAY, cal1.get(Calendar.HOUR_OF_DAY));

cal0.set(Calendar.MINUTE, cal1.get(Calendar.MINUTE));

cal0.set(Calendar.SECOND, cal1.get(Calendar.SECOND));

return cal0.getTime();

}

/**

* String日期+时间

* @param date 日期

* @param time 时间

* @return Date类型的日期

* @throws ParseException

*/

public static Date addTime(String date, String time) throws ParseException {

return add(parseDate(date), parseTime(time));

}

/**

* 返回当前日期时间

* @return 当前日期时间的Date类型

*/

public static Date getDateTime() {

return Calendar.getInstance().getTime();

}

/**

* 返回String型当前时间

* @return 当前日期时间的String类型

*/

public static String getDateTimeStr() {

return format(getDateTime());

}

/**

* 返回String型当前日期的长类型:日期、时间

* @return 返回String型当前日期的长类型:日期、时间

* @throws ParseException

*/

public static String getLongDateTimeStr() {

return formatDateTime(getDateTime());

}

/**

* 返回给定日期的日期时间

* @param date

* @return 给定日期的日期、当前时间Date类型的值

*/

public static Date getDateTime(String date) throws ParseException {

return add(parse(date), getTime());

}

/**

* 返回String型给定日期的日期时间

* @param date

* @return String类型的日期值

* @throws ParseException

*/

public static String getDateTimeStr(String date) throws ParseException {

return format(getDateTime(date));

}

/**

* 返回String型给定日期的日期时间用于DB2的日期

* @param date

* @return String类型的日期值1970 00:00:00

* @throws ParseException

*/

public static String getDateTimeForTimeStamp(String date) throws ParseException {

return format(getDateTime(date))+" 00:00:00";

}

/**

* 返回String型给定日期的日期时间用于DB2的日期

* @param date

* @return String类型的日期值1970 00:00:00

* @throws ParseException

*/

public static String getDateForTimeStamp(String date) throws ParseException {

return format(parse(date))+" 00:00:00";

}

/**

* 返回当前日期

* @return 当前日期Date类型

*/

public static Date getDate() {

Calendar cal = Calendar.getInstance();

cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));

return new Date(cal.getTimeInMillis());

}

/**

* 返回String当前日期

* @return 当前日期String类型

*/

public static String getDateStr() {

return formatDate(getDate());

}

/**

* 返回当前时间

* @return 当前时间Date类型

*/

public static Date getTime() {

Calendar cal = Calendar.getInstance();

cal.set(1970, 0, 1, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal

.get(Calendar.SECOND));

return new Date(cal.getTimeInMillis());

}

/**

* 返回String当前时间

* @return 当前时间String类型

*/

public static String getTimeStr() {

return formatTime(getTime());

}

/**

* 返回默认格式的字符串日期

* @param date

* @return yyyy-MM-dd格式的字符串日期

*/

public static String formatDate(Date date) {

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("yyyy-MM-dd");

return sf.format(date);

}

/**

* 返回默认格式的字符串时间

* @param time

* @return HH:mm:ss格式的字符串时间

*/

public static String formatTime(Date time) {

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getTimeInstance();

sf.applyPattern("HH:mm:ss");

return sf.format(time);

}

/**

* 返回默认格式的字符串日期 时间

* @param date

* @return yyyy-MM-dd HH:mm:ss格式的字符串日期 时间

*/

public static String formatDateTime(Date date){

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("yyyy-MM-dd HH:mm:ss");

return sf.format(date);

}

/**

* 返回字符串日期

* @param date

* @return yyyy-MM-dd格式的字符串日期

*/

public static String format(Date date) {

SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd");

return dateF.format(date);

}

/**

* 返回默认格式的字符串日期 时间

* @param date

* @return yyyy-MM-dd HH:mm:ss SSS格式的字符串日期 时间

*/

public static String formatDateTimeMillisByDate(Date date){

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("yyyy-MM-dd HH:mm:ss.SSS");

return sf.format(date);

}

/**

* 返回默认格式的字符串日期 时间

* @return yyyy-MM-dd HH:mm:ss SSS格式的字符串日期 时间

*/

public static String formatDateTimeMillis(){

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("yyyy-MM-dd HH:mm:ss SSS");

return sf.format(getDateTime());

}

/**

* 返回默认格式的字符串日期 时间

* @return yyyyMMddHHmmssSSS格式的字符串日期 时间

*/

public static String formatDateTimeMillisString(){

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("yyyyMMddHHmmssSSS");

return sf.format(getDateTime());

}

/**

* 返回默认格式的字符串日期 时间

*

* @return yyyy-MM-dd HH:mm:ss 格式的字符串日期 时间

*/

public static String formatDateTime(){

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("yyyy-MM-dd HH:mm:ss");

return sf.format(getDateTime());

}

/**

* 返回默认格式的字符串日期

*

* @return yyyyMMdd格式的字符串日期

*/

public static String formatDate(){

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("yyyyMMdd");

return sf.format(getDateTime());

}

/**

* 返回默认格式的字符串时间

*

* @return HHmmss格式的字符串时间

*/

public static String formatTime(){

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("HHmmss");

return sf.format(getDateTime());

}

/**

* 返回年

* @param date

* @return 年

* @throws ParseException

*/

public static int getYear(Date date) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

return cal.get(Calendar.YEAR);

}

/**

* 返回年

* @param date

* @return 年

* @throws ParseException

*/

public static int getYear(String date) throws ParseException {

return getYear(parseDate(date));

}

/**

* 判断是否为闰年

* @param year

* @return boolean

*/

public static boolean isLeapYear(int year) {

GregorianCalendar cal = new GregorianCalendar();

return cal.isLeapYear(year);

}

/**

* 返回月

* @param date

* @return 月

* @throws ParseException

*/

public static int getMonth(Date date) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

return cal.get(Calendar.MONTH);

}

/**

* 返回月

* @param date

* @return 月

* @throws ParseException

*/

public static int getMonth(String date) throws ParseException {

return getMonth(parseDate(date));

}

/**

* 返回日

* @param date

* @return 日

* @throws ParseException

*/

public static int getDay(Date date) {

Calendar cal = Calendar.getInstance();

cal.setTime(date);

return cal.get(Calendar.DATE);

}

/**

* 返回日

* @param date

* @return 日

* @throws ParseException

*/

public static int getDay(String date) throws ParseException {

return getDay(parseDate(date));

}

/**

* 比较两个时间大小

* @param date1

* @param date2

* @return true date1>=date2; false date1 < date2

* @throws ParseException

*/

public static boolean greatEqual(String date1, String date2) throws ParseException {

return parseDate(date1).getTime() >= parseDate(date2).getTime();

}

/**

* 比较两个时间是否相等

* @param date1

* @param date2

* @return true date1>=date2; false date1 < date2

* @throws ParseException

*/

public static boolean equal(String date1, String date2) throws ParseException {

return parseDate(date1).getTime() == parseDate(date2).getTime();

}

public static boolean great(String date1, String date2) throws ParseException {

return parseDate(date1).getTime() > parseDate(date2).getTime();

}

/**

* 比较两个时间大小(无日期)

* @param date1

* @param date2

* @return true date1>=date2; false date1 < date2

* @throws ParseException

*/

public static boolean greatTime(String date1, String date2) throws ParseException {

return parseTime(date1).getTime() >= parseTime(date2).getTime();

}

/**

* 比较两个时间大小

* @param date1

* @param date2

* @return true date1<date2; false date1 >= date2

* @throws ParseException

*/

public static boolean less(String date1, String date2) throws ParseException {

return parseDate(date1).getTime() < parseDate(date2).getTime();

}

public static boolean isZero(String date) throws ParseException{

if(date==null || date.trim().equals(""))return true;

return parseDate(date).getTime() <= parseDate("1901-1-1").getTime();

}

public static int getDayOfWeek(Date date){

Calendar cal = Calendar.getInstance();

cal.setTime(date);

return cal.get(Calendar.DAY_OF_WEEK);

}

private static String type;

public static void setType(String type) {

GenernalDate.type = type;

}

public static Date parseDateNorm(String date) throws ParseException {

//long offsec=(Long.valueOf(date)-25569)*3600*24*1000;

//SimpleDateFormat dateF = (SimpleDateFormat)SimpleDateFormat.getDateInstance();

//dateF.format(Long.valueOf(date));

//SimpleDateFormat dateff= new SimpleDateFormat("yyyy-MM-dd");

SimpleDateFormat dateff= new SimpleDateFormat("yyyy-MM-dd");

return dateff.parse(date);

//return d;

}

public static Date formatDateTimeToDate(Date date) throws ParseException {

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

sf.applyPattern("yyyy-MM-dd HH:mm:ss");

String temp=sf.format(date+" 0:00:00");

return sf.parse(temp);

}

/**

* 判断时间date1是否在时间date2之前,不能用于日期

*/

public static boolean isDateBefore(String date1, String date2) {

if(date2.equals("")){

return false;

}else if(date1.equals("")){

return true;

}

try {

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

return df.parse(date1).before(df.parse(date2));

} catch (ParseException e) {

return false;

}

}



/**

* 日期转换

* @param date 三种格式 20100421153055|20100421|153055

* @return

* @throws ParseException

* @throws ApplicationException

*/

public static Date parse(long date)throws ApplicationException{

String dateStr = String.valueOf(date);

boolean isDate = false,isTime = false,isDateTime = false;

if(dateStr.length()==DATETIME_LENGTH){

isDateTime = true;

}else if(dateStr.length()==DATE_LENGTH){

isDate = true;

}else if(dateStr.length()==TIME_LENGTH){

isTime = true;

}else {

throw new ApplicationException("Date format is not correct["+dateStr+"]");

}

SimpleDateFormat sf = (SimpleDateFormat) DateFormat.getDateInstance();

try{

if (isDateTime) { //日期时间

sf.applyPattern("yyyyMMddHHmmss");

return sf.parse(dateStr);

} else if (isDate) {

sf.applyPattern("yyyyMMdd");

return sf.parse(dateStr);

} else if (isTime) {

sf.applyPattern("HHmmss");

return sf.parse(dateStr);

}

}catch(ParseException pe){

throw new ApplicationException(pe.getMessage());

}

return new Date(0);

}

/**

* Date类型(日期) 转换为 int 类型

* @param dateTime

* @return long 20100421132630

*/

public static int getIntegerDate(Date dateTime){

SimpleDateFormat sf = (SimpleDateFormat)DateFormat.getInstance();

sf.applyPattern("yyyyMMdd");

return Integer.parseInt(sf.format(dateTime));

}

/**

* 返回日期

* @param date

* @return Date yyyyMMdd

* @throws ParseException

*/

public static Date parseDate(Date date) throws ParseException {

SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd");

return dateF.parse(String.valueOf(date));

}

/**

* 读取当前的日期+时间

* return long 20100421132630

*/

public static long getNumericDateTime(){

SimpleDateFormat sf = (SimpleDateFormat)DateFormat.getInstance();

sf.applyPattern("yyyyMMddHHmmss");

String dateTime = sf.format(Calendar.getInstance().getTime());

return Long.parseLong(dateTime);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: