Java日期格式转换,计算工具

Java日期格式转换,计算工具,以及月份,周次等日历相关内容查找工具

包含功能:

  1. 获取当前时间
  2. 将 java.util.Date 转换为指定格式的字符串
  3. 将 时间格式的字符串 转换 java.util.Date
  4. 判断两个时间是否是属于同一周
  5. 计算两个日期之间隔了多少秒/小时/天等
  6. 比较俩个时间字符串的时间先后顺序
  7. 获取某月的第一天和最后一天,如 2017-08-01,则获得2017-07-01 00:00:00,2017-07-31 00:00:00
  8. 获得某年的第几周次的第一天时间(周日为一周的开始)
  9. 日期的任意加减
  10. 优美的时间格式处理 比如 “今天 16:31”,“明天 16:31”,“2029年6月24日17:33”等。还有处理成带有星期的时间展示,比如 “2018-01-01 星期一”,“2018-01-01 星期一 18:32”等
  11. 计算两个时间之间的时间差,并自动展示给出来二者的时间,支持刚刚,已等待多少天/小时/分钟等等
  12. 获得本周的 周一时间或周日时间

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 日期格式转换,计算工具
 * 
 * @author 才揽
 * */
public class DateKit {
	private static final String DATE_PATTERN = "yyyy-MM-dd";
	private static final String DATE_PATTERN_TIME = "yyyy-MM-dd HH:mm:ss";
	private static final String DATE_PATTERN_YMD_HM = "yyyy-MM-dd HH:mm";
	private static final String DATE_PATTERN_MD_HM = "MM-dd HH:mm";
	private static final String DATE_PATTERN_HM = "HH:mm"; 
	private static final String BLANK = " ";
	private static final int[] WEEK_NO_ARRYA = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
			17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,
			40,41,42,43,44,45,46,47,48,49,50,51,52,53}; 
	private static final int[] MONTH_NO_ARRYA = new int[] {1,2,3,4,5,6,7,8,9,10,11,12}; 
	private static final String[] WEEKDAYS = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
	
	/**
	 * 获取当前时间
	 * 
	 * @return java.util.Date
	 */
	public static Date getNowDate() {
		return new Date();
	}
	
	/**
	 * 将 java.util.Date 转换为指定格式的字符串
	 * 字符串格式 yyyy-MM-dd
	 * 
	 * @param date
	 * @retrun String 字符串格式 yyyy-MM-dd
	 * */
	public static String toStr(Date date) {
		return toStr(date, DATE_PATTERN);
	}
	
	/**
	 * 将 java.util.Date 转换为指定格式的字符串
	 * 字符串格式 yyyy-MM-dd HH:mm:ss
	 * 
	 * @param date
	 * @retrun String 字符串格式 yyyy-MM-dd
	 * */
	public static String toTimeStr(Date date) {
		return toStr(date, DATE_PATTERN_TIME);
	}
	
	/**
	 * 将 java.util.Date 转换为指定格式的字符串
	 * 
	 * @param date 时间
	 * @param pattern 格式,如 yyyy-MM-dd
	 * @return String 字符串格式 pattern
	 * */
	public static String toStr(Date date, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}
	
	/**
	 * 将 时间格式的字符串 转换 java.util.Date
	 * 
	 * @param dateStr 时间格式的字符串
	 * @return java.util.Date
	 * */
	public static Date toDate(String dateStr) {
		if (strIsBlank(dateStr)) {
			return null;
		}
		dateStr = dateStr.trim();
		int length = dateStr.length();
		try {
			if (length == DATE_PATTERN_TIME.length()) {
				SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN_TIME);
				try {
					return sdf.parse(dateStr);
				} catch (ParseException e) {
					dateStr = dateStr.replace(".", "-");
					dateStr = dateStr.replace("/", "-");
					return sdf.parse(dateStr);
				}
			} else if (length == DATE_PATTERN.length()) {
				SimpleDateFormat sdfDate = new SimpleDateFormat(DATE_PATTERN);
				try {
					return sdfDate.parse(dateStr);
				} catch (ParseException e) {
					dateStr = dateStr.replace(".", "-");
					dateStr = dateStr.replace("/", "-");
					return sdfDate.parse(dateStr);
				}
			} else {
				throw new IllegalArgumentException("The date format is not supported for the time being");
			}
		} catch (ParseException e) {
			throw new IllegalArgumentException("The date format is not supported for the time being");
		}
	}
	
	/**
	 * 判断两个时间是否是属于同一周
	 * 
	 * @param date1
	 * @param date2
	 * @return boolean true、是,false、否
	 * */
	public static boolean isDateInSameWeek(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		Calendar cal2 = Calendar.getInstance();
		cal1.setTime(date1);
		cal2.setTime(date2);
		int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
		if (subYear == 0) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		}else if (subYear == 1 && cal2.get(Calendar.MONTH) == 11) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		}else if (subYear == -1 && cal1.get(Calendar.MONTH) == 11) {
			if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
				return true;
		}
		return false;
	}

	/**
	 * 计算两个日期之间隔了多少秒
	 * 
	 * @param start
	 * @param end
	 * @return int
	 */
	public static int getDateSecondSpace(Date start, Date end) {
		int hour = (int) ((end.getTime() - start.getTime()) / 1000);
		return hour;
	}
	
	/**
	 * 返回两个日期之间隔了多少小时
	 * 
	 * @param start
	 * @param end
	 * @return int
	 */
	public static int getDateHourSpace(Date start, Date end) {
		return getDateSecondSpace(start, end) / 3600;
	}

	/**
	 * 返回两个日期之间隔了多少天
	 * 
	 * @param start
	 * @param end
	 * @return int
	 */
	public static int getDateDaySpace(Date start, Date end) {
		int day = getDateHourSpace(start, end) / 24;
		return day;
	}
	
	/**
	 * 比较俩个时间字符串大小,比较俩个时间字符串的时间先后顺序
	 * 
	 * @param start
	 * @param end
	 * @return boolean 返回true ,第一个参数大,false 第二个参数大
	 */
	public static boolean compareTwoTime(String start, String end) {
		long flag = 0;
		Date date1 = null;
		Date date2 = null;
		try {
			date1 = toDate(start);
			date2 = toDate(end);
		} catch (Exception e) {
			throw new IllegalArgumentException("The date format is not supported for the time being");
		}
		flag = date1.getTime() - date2.getTime();
		return flag > 0 ? true : false;
	}
	
	/***
	 * 获取前一个月的第一天和最后一天 
	 * 形式如当前时间是2017-08-01 17:17:52,则获得2017-07-01 00:00:00,2017-07-31 00:00:00
	 *          
	 * @return string[]
	 */
	public static String[] getLastMonthFirstDayAndLastDay() {
		String[] temp = new String[2];
		// 获取前一个月第一天
		Calendar calendar1 = Calendar.getInstance();
		calendar1.add(Calendar.MONTH, -1);
		calendar1.set(Calendar.DAY_OF_MONTH, 1);
		String firstDay = toStr(calendar1.getTime()) + " 00:00:00";
		// 获取前一个月最后一天
		Calendar calendar2 = Calendar.getInstance();
		calendar2.set(Calendar.DAY_OF_MONTH, 0);
		String lastDay = toStr(calendar2.getTime()) + " 00:00:00";
		temp[0] = firstDay;
		temp[1] = lastDay;
		return temp;
	}
	
	
	/**
	 * 获得某年的第几周次的第一天时间(周日为一周的开始)
	 * 
	 * @param year 年
	 * @param weekNo 周次
	 * @return java.util.Calendar
	 * */
	public static Calendar getFirstDayOfWeekNo(Integer year,Integer weekNo){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, weekNo);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); 
        return cal;    
    }
	
	/**
	 * 获得周次信息
	 * 
	 * @return 周次信息,一年一共52-53周
	 * */
	public static int[] getWeekNoArray() {
		return WEEK_NO_ARRYA;
	}
	
	/**
	 * 获得月份信息
	 * 
	 * @return 周次信息,一年一共12个月
	 * */
	public static int[] getMonthNoArray() {
		return MONTH_NO_ARRYA;
	}
	
	/**
	 * 日期加上自定义天数并返回
	 * 
	 * @param date 时间
	 * @param days 需要加减的天数
	 * */
	public static Date addDays(Date date, int days) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_MONTH, days);
		return cal.getTime();
	}
	
	/**
	 * 优美的时间格式处理
	 *  比如  今天 16:31,明天 16:31,2029年6月24日17:33 等
	 *  
	 * @param date 时间
	 * @return String 今天 16:31
	 * */
	public static String toGracefulStr(Date date) {
		if(date == null) {
			return "";
		}
		Map<String, Long> yesterTodayTomorrow = getYesterTodayTomorrowTimeStamp();
		long todayTime = yesterTodayTomorrow.get("todayTime");
		long tomorrowTime = yesterTodayTomorrow.get("tomorrowTime");
		long yesterdayTime = yesterTodayTomorrow.get("yesterdayTime");
		long yearTime = yesterTodayTomorrow.get("yearTime");
		long dateTime = date.getTime();
		// 86400000=24*60*60*1000 一天
		long oneDay = 86400000;
		if( dateTime - tomorrowTime > oneDay ) {
			return yearDivided(date, yearTime, dateTime);
		}
		if( dateTime - tomorrowTime < oneDay &&  dateTime - tomorrowTime > 0) {
			return "明天 " + toStr(date, DATE_PATTERN_HM);
		}
		if( dateTime - tomorrowTime < 0 && dateTime - todayTime < oneDay && dateTime - todayTime > 0) {
			return "今天 " + toStr(date, DATE_PATTERN_HM);
		}
		if( dateTime - yesterdayTime < oneDay && dateTime - yesterdayTime > 0) {
			return "昨天 " + toStr(date, DATE_PATTERN_HM);
		}
		if( dateTime - yesterdayTime < 0) {
			return yearDivided(date, yearTime, dateTime);
		}else {
			return yearDivided(date, yearTime, dateTime);
		}
	}
	
	/**
	 * 优美的时间格式处理,处理成带有星期的时间展示
	 *  比如  2018-01-01 星期一
	 * 
	 * @param date 时间
	 * @return String 2018-01-01 星期一
	 * */
	public static String toDayWeek(Date date) {
		if(date == null) {
			return "";
		}
		Calendar cal = Calendar.getInstance(); 
		cal.setTime(date);
		// 指示一个星期中的某天。
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0) {
			w = 0;
		}
		return toStr(date) + BLANK + WEEKDAYS[w];
	}
		
	/**
	 * 优美的时间格式处理,处理成带有星期的时间展示并带有时分
	 *  比如  2018-01-01 星期一 18:32
	 * 
	 * @param date
	 * @return String 2018-01-01 星期一 18:32
	 * */
	public static String toDayWeekTime(Date date) {
		if(date == null) {
			return "";
		}
		Calendar cal = Calendar.getInstance(); 
		cal.setTime(date);
		// 指示一个星期中的某天。
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0) {
			w = 0;
		}
		StringBuilder timeStr = new StringBuilder()
				.append(toStr(date))
				.append(BLANK)
				.append(WEEKDAYS[w])
				.append(BLANK)
				.append(toStr(date, DATE_PATTERN_HM));
		return timeStr.toString();
	}
	
	/**
	 * 计算两个时间之间的时间差,并自动展示给出来二者的时间,支持刚刚,已等待多少天/小时/分钟等等
	 * 
	 * @param indexDate 对比的时间标准
	 * @param date 处理时的时间
	 * @return String 返回date较之indexDate度过了多久时间,比如:刚刚、已等待 1 天、已等待 1小时等
	 * */
	public static String toWaitTimeStr(Date indexDate, Date date) {
		long todayTime = indexDate.getTime();
		long dateTime = date.getTime();
		//一天:86400000=24*60*60*1000 
		long nd = 86400000;
		// 一小时:1000 * 60 * 60
	    long nh = 3600000;
	    // 一分钟:1000 * 60
	    long nm = 60000;
	    // 获得两个时间的毫秒时间差异
		long subTime = todayTime - dateTime;
		if(subTime < 300000) {
	    	return "刚刚";
	    }
	    long day = subTime / nd;
	    long hour = subTime % nd / nh;
	    long min = subTime % nd % nh / nm;
	    StringBuilder sb = new StringBuilder()
	    		.append("已等待");
	    if(day > 0) {
	    	sb.append(day)
	    	.append("天");
	    }
	    if(hour > 0) {
	    	sb.append(hour)
	    	.append("小时");
	    }
	    if(min > 0) {
	    	sb.append(min)
	    	.append("分钟");
	    }
	    return sb.toString();
		
	}

	/**
	 * 获得本周的 周一时间
	 * 星期日为一周的第一天	SUN	MON	TUE	WED	THU	FRI	SAT
	 * 值DAY_OF_WEEK返回值	 1	2	3	4	5	6	7
	 * 
	 * @return Calendar
	 * */
	public static Calendar getBeginDayOfWeek() {
		Calendar cal = Calendar.getInstance();
		int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
		cal.add(Calendar.DATE, 2 - dayofweek);
		return cal;
	}
	
	/**
	 * 获得本周的 周日时间
	 * 星期日为一周的第一天	SUN	MON	TUE	WED	THU	FRI	SAT
	 * 值DAY_OF_WEEK返回值	 1	2	3	4	5	6	7
	 * 
	 * @return Calendar
	 * */
	public static Calendar getEndDayOfWeek() {
		Calendar cal = getBeginDayOfWeek();
		cal.add(Calendar.DAY_OF_WEEK, 6);
		return cal;
	}
	
	/**
	 * 年份划分辅助方法
	 * 
	 * @param date
	 * @param yearTime
	 * @param dateTime
	 * */
	private static String yearDivided(Date date, long yearTime, long dateTime) {
		if(dateTime < yearTime) {
			return toStr(date, DATE_PATTERN_YMD_HM);
		}else {
			return toStr(date, DATE_PATTERN_MD_HM);
		}
	}
	
	/**
	 * 获得昨天,今天,明天 时间戳
	 * 
	 * @return HashMap
	 * */
	private static Map<String, Long> getYesterTodayTomorrowTimeStamp() {
		// 今天
		Calendar today = Calendar.getInstance();
		today.set(Calendar.HOUR_OF_DAY, 0);
		today.set(Calendar.MINUTE, 0);
		today.set(Calendar.SECOND, 0);
		// 明天
		Calendar tomorrow = Calendar.getInstance();
		tomorrow.add(Calendar.DAY_OF_YEAR, 1);
		tomorrow.set(Calendar.HOUR_OF_DAY, 0);
		tomorrow.set(Calendar.MINUTE, 0);
		tomorrow.set(Calendar.SECOND, 0);
		// 昨天
		Calendar yesterday = Calendar.getInstance();
		yesterday.add(Calendar.DAY_OF_YEAR, -1);
		yesterday.set(Calendar.HOUR_OF_DAY, 0);
		yesterday.set(Calendar.MINUTE, 0);
		yesterday.set(Calendar.SECOND, 0);
		// 年份划分
		Calendar yearCalendar = Calendar.getInstance();
		yearCalendar.set(today.get(Calendar.YEAR), 0, 1, 0, 0, 0);
		
		long todayTime = today.getTime().getTime();
		long tomorrowTime = tomorrow.getTime().getTime();
		long yesterdayTime = yesterday.getTime().getTime();
		long yearTime = yearCalendar.getTime().getTime();
		
		Map<String, Long> data = new HashMap<>();
		data.put("todayTime", todayTime);
		data.put("tomorrowTime", tomorrowTime);
		data.put("yesterdayTime", yesterdayTime);
		data.put("yearTime", yearTime);
		return data;
	}
	
	/**
	 * 字符串判空辅助方法
	 * 当字符串为 null或者内部字符全部为 ' ' '\t' '\n' '\r' 这四类字符时返回 true
	 * 
	 * @param str
	 * @return boolean
	 */
	private static boolean strIsBlank(String str) {
		if (str == null) {
			return true;
		}
		for (int i = 0, len = str.length(); i < len; i++) {
			if (str.charAt(i) > ' ') {
				return false;
			}
		}
		return true;
	}
}

测试模块:

	// 测试模块
	public static void main(String[] args) {
		System.out.println("当前时间:" + toStr(getNowDate()));
		// 日期加 2  天
		Date addDays1 = addDays(getNowDate(), 2);
		// 日期加 -3  天
		Date addDays2 = addDays(getNowDate(), -3);
		// 日期加 -400  天
		Date addDays3 = addDays(getNowDate(), -400);
		System.out.println("优雅时间当前时间:" + toGracefulStr(getNowDate()));
		System.out.println("优雅时间addDays1:" + toGracefulStr(addDays1));
		System.out.println("优雅时间addDays2:" + toGracefulStr(addDays2));
		System.out.println("优雅时间addDays3:" + toGracefulStr(addDays3));
		System.out.println("带周的时间addDays1:" + toDayWeek(addDays1));
		System.out.println("带周的时间addDays2:" + toDayWeekTime(addDays2));
	}

运行截图:
Java日期格式转换,计算工具_第1张图片

你可能感兴趣的:(java)