Java时间工具类Date的常用处理方法

2022-11-13 08:11:56 时间 工具 常用

前言

Date 类

Date 类表示系统特定的时间戳,可以精确到毫秒。Date 对象表示时间的默认顺序是星期、月、日、小时、分、秒、年。

构造方法

Date 类有如下两个构造方法。

Date():此种形式表示分配 Date 对象并初始化此对象,以表示分配它的时间(精确到毫秒),使用该构造方法创建的对象可以获取本地的当前时间。

Date(long date):此种形式表示从 GMT 时间(格林尼治时间)1970 年 1 月 1 日 0 时 0 分 0 秒开始经过参数 date 指定的毫秒数。

这两个构造方法的使用示例如下:

Date date1 = new Date();    // 调用无参数构造函数
System.out.println(date1.toString());    // 输出:Wed May 18 21:24:40 CST 2016
Date date2 = new Date(60000);    // 调用含有一个long类型参数的构造函数
System.out.println(date2);    // 输出:Thu Jan 0108:01:00 CST 1970

Date 类的无参数构造方法获取的是系统当前的时间,显示的顺序为星期、月、日、小时、分、秒、年。

Date 类带 long 类型参数的构造方法获取的是距离 GMT 指定毫秒数的时间,60000 毫秒是一分钟,而 GMT(格林尼治标准时间)与 CST(中央标准时间)相差 8 小时,也就是说 1970 年 1 月 1 日 00:00:00 GMT 与 1970 年 1 月 1 日 08:00:00 CST 表示的是同一时间。 因此距离 1970 年 1 月 1 日 00:00:00 CST 一分钟的时间为 1970 年 1 月 1 日 00:01:00 CST,即使用 Date 对象表示为 Thu Jan 01 08:01:00 CST 1970。

常用方法

 

public final class DateUtils {
	
	public static final SimpleDateFORMat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
	
	public static final SimpleDateFormat yyyy_MM_dd = new SimpleDateFormat("yyyy-MM-dd");
	
    public static final SimpleDateFormat DEFAULT_FORMAT = yyyy_MM_dd;
	
	public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss_SSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");	
	
	public static final SimpleDateFormat yyyy_MM_dd_HH_mm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
	public static final SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");	
	
	public static final SimpleDateFormat yyyyMMddHHmmssSSS = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	
	public static final SimpleDateFormat yyyy_MM_ddHH_mm_ssSSS = new SimpleDateFormat("yyyy-MM-ddHH:mm:ssSSS");
		
	public static final SimpleDateFormat MMdd = new SimpleDateFormat("MMdd");
 
	
    private DateUtils() {}
    
    
    public static Date parse(String date) throws ParseException{
        return DEFAULT_FORMAT.parse(date);
    }
    
    public static Date parse(String date, String format) throws ParseException{
        return new SimpleDateFormat(format).parse(date);
    }    
 
    
    public static String getToday(String format) {
        return new SimpleDateFormat(format).format(new Date());
    }
    
    
    public static String format(Date date, SimpleDateFormat format) {
		if (date == null) {
			return null;
		}
		return format.format(date);
    }
    
    
    public static String getToday(SimpleDateFormat format) {
        return format.format(new Date());
    }
 
    
    public static String getToday() {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    }
    
    public static String getTodayMMdd() {
        return MMdd.format(new Date());
    } 
    
	public static int monthDifference(Calendar one, Calendar two) {
		if (null == one || null == two) {
			throw new NullPointerException("参数对象为空。");
		}
		Calendar after = one;
		Calendar before = two;
		if (one.before(two)) {
			after = two;
			before = one;
		}
		int deffYear = Math.abs(after.get(Calendar.YEAR) - before.get(Calendar.YEAR));
		int deffMonth = after.get(Calendar.MONTH) - before.get(Calendar.MONTH);
		  //错误的逻辑块
		return deffYear * 12 + deffMonth;
	}
 
	
	public static int monthDifference(Date one, Date two) {
		Calendar first = new GreGorianCalendar();
		first.setTime(one);
		Calendar second = new GregorianCalendar();
		second.setTime(two);
		return monthDifference(first, second);
	}
 
	
	public static int monthDifference(String one, String two)
			throws ParseException {
		Format format = new SimpleDateFormat("yyyy-MM-dd");
		Date first = (java.util.Date) format.parseObject(one);
		Date second = (java.util.Date) format.parseObject(two);
		return monthDifference(first, second);
	}
 
	
	public static boolean isLastDayOfMonth(Calendar calendar) {
		Calendar today = calendar;
		Calendar tomorrow = (Calendar) calendar.clone();
		tomorrow.add(Calendar.DAY_OF_MONTH, 1);
		int todayYear = today.get(Calendar.YEAR);
		int todayMonth = today.get(Calendar.MONTH) + 1;
		int tomorrowYear = tomorrow.get(Calendar.YEAR);
		int tomorrowMonth = tomorrow.get(Calendar.MONTH) + 1;
		//是否为当月最后一天
		if (tomorrowYear > todayYear || (tomorrowYear == todayYear && tomorrowMonth > todayMonth)) {
			return true;
		}
		return false;
	}
 
	
	public static boolean isLastDayOfMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return isLastDayOfMonth(calendar);
	}
 
	
	public static boolean isLastDayOfMonth() {
		return isLastDayOfMonth(Calendar.getInstance());
	}
	
	
	public static String convertMonth(int month) {
		switch (month) {
		case Calendar.JANUARY:
			return "一月";
		case Calendar.FEBRUARY:
			return "二月";
		case Calendar.MARCH:
			return "三月";
		case Calendar.APRIL:
			return "四月";
		case Calendar.MAY:
			return "五月";
		case Calendar.JUNE:
			return "六月";
		case Calendar.JULY:
			return "七月";
		case Calendar.AUGUST:
			return "八月";
		case Calendar.SEPTEMBER:
			return "九月";
		case Calendar.OCTOBER:
			return "十月";
		case Calendar.NOVEMBER:
			return "十一月";
		case Calendar.DECEMBER:
			return "十二月";
		default:
			throw new IllegalArgumentException("表示月份的参数无效:" + month);
		}
	}
 
	
	public static String convertDayOfWeek(int dayOfWeek) {
		switch (dayOfWeek) {
		case Calendar.SUNDAY:
			return "周日";
		case Calendar.MONDAY:
			return "周一";
		case Calendar.TUESDAY:
			return "周二";
		case Calendar.WEDNESDAY:
			return "周三";
		case Calendar.THURSDAY:
			return "周四";
		case Calendar.FRIDAY:
			return "周五";
		case Calendar.SATURDAY:
			return "周六";
		default:
			throw new IllegalArgumentException("参数无效:" + dayOfWeek);
		}
	}
 
	
	public static String convertDayOfWeek2(int dayOfWeek) {
		switch (dayOfWeek) {
		case Calendar.SUNDAY:
			return "星期天";
		case Calendar.MONDAY:
			return "星期一";
		case Calendar.TUESDAY:
			return "星期二";
		case Calendar.WEDNESDAY:
			return "星期三";
		case Calendar.THURSDAY:
			return "星期四";
		case Calendar.FRIDAY:
			return "星期五";
		case Calendar.SATURDAY:
			return "星期六";
		default:
			throw new IllegalArgumentException("参数无效:" + dayOfWeek);
		}
	}
 
	
	public static String getTodayOfWeek2() {
		return convertDayOfWeek2(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));
	}
 
	
	public static String getTodayOfWeek() {
		return convertDayOfWeek(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));
	}  
    
    public static String getDateByMillSeconds(long millSeconds, String parseStr){        
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(parseStr);  
        String sb=format.format(getDateByMillSeconds(millSeconds));  
        return sb;
    }
    
    public static Date getDateByMillSeconds(long millSeconds){
        Date date = new Date(millSeconds);  
        GregorianCalendar GC = new GregorianCalendar();   
        gc.setTime(date);  
        return gc.getTime();
    }
    
    public static String getFirstDayByCurrentMonth(){
        Calendar calendar  =   new  GregorianCalendar();
        calendar.set( Calendar.DATE,  1 );
        SimpleDateFormat simpleFormate  =   new  SimpleDateFormat( "yyyy-MM-dd" );
        return simpleFormate.format(calendar.getTime());
    }
    
    
    public static String getLastDayByCurrentMonth(){
        Calendar calendar  =   new  GregorianCalendar();
        calendar.set( Calendar.DATE,  1 );
        calendar.roll(Calendar.DATE,  - 1 );
        SimpleDateFormat simpleFormate  =   new  SimpleDateFormat( "yyyy-MM-dd" );
        return simpleFormate.format(calendar.getTime());
    }
    
    public static Long getRealWorkminutes(Date realStartDate, Date realEndDate) throws Exception{
        BigDecimal realWorkminutes = new BigDecimal("0");
        long startTime = 0l;
        long endTime = 0l;
        long timeInterval = 0l; 
        if(realStartDate != null && realEndDate != null) {
            startTime = realStartDate.getTime();
            endTime = realEndDate.getTime();
            timeInterval = endTime - startTime;
            if(timeInterval > 0){
                int day = (int)timeInterval/(24*60*60*1000);        
                int hour = (int)timeInterval/(60*60*1000)-day*24;          
                int min = (int)(timeInterval/(60*1000))-day*24*60-hour*60;
                if(day >= 1){
                    realWorkminutes = new BigDecimal(day*8*60);
                    if(hour >= 1){
                        realWorkminutes = realWorkminutes.add(new BigDecimal(hour*20));
                    }
                    if(min >=1){
                        realWorkminutes = realWorkminutes.add(new BigDecimal(min));
                    }
                }else{
                    if(hour >= 1){
                        realWorkminutes = realWorkminutes.add(new BigDecimal(hour*60>=480?480:hour*60));
                    }
                    if(min >=1){
                        realWorkminutes = realWorkminutes.add(new BigDecimal(min));
                    }
                    if(realWorkminutes.compareTo(new BigDecimal(480)) > 0) realWorkminutes = new BigDecimal(480);
                }
            }
        }
        return Long.valueOf(String.valueOf(realWorkminutes));
    }
    
    public static int getDaysBetween(String beginDate, String endDate)
			throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date bDate = format.parse(beginDate);
		Date eDate = format.parse(endDate);
		return getDaysBetween(bDate, eDate);
	}
    
    public static int getDaysBetween(Date beginDate, Date endDate)
			throws ParseException {
		Calendar g1 = new GregorianCalendar();
		g1.setTime(beginDate);
		Calendar g2 = new GregorianCalendar();
		g2.setTime(endDate);
		
		int elapsed = 0;
		  GregorianCalendar gc1, gc2;
 
		  if (g2.after(g1)) {
		   gc2 = (GregorianCalendar) g2.clone();
		   gc1 = (GregorianCalendar) g1.clone();
		  } else {
		   gc2 = (GregorianCalendar) g1.clone();
		   gc1 = (GregorianCalendar) g2.clone();
		  }
 
		  gc1.clear(Calendar.MILLISECOND);
		  gc1.clear(Calendar.SECOND);
		  gc1.clear(Calendar.MINUTE);
		  gc1.clear(Calendar.HOUR_OF_DAY);
 
		  gc2.clear(Calendar.MILLISECOND);
		  gc2.clear(Calendar.SECOND);
		  gc2.clear(Calendar.MINUTE);
		  gc2.clear(Calendar.HOUR_OF_DAY);
 
		  while (gc1.before(gc2)) {
		   gc1.add(Calendar.DATE, 1);
		   elapsed++;
		  }
		  return elapsed;
	}    
    
    
    public static long getFinalTime(long startTime, long timeInterval) {
        return startTime + timeInterval;
    }
 
    
}

到此这篇关于Java时间工具类Date的常用处理方法的文章就介绍到这了,更多相关Java时间工具类Date内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章