目 录CONTENT

文章目录

Java实用工具类二:时间格式转换工具

芈亓
2022-03-11 / 0 评论 / 0 点赞 / 837 阅读 / 10,294 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-15,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
  • 此文仅对自己工作中用到的类进行总结,方便以后的使用。
    类一:
package com.cn.hnust.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class DateUtil {
    /**
     * 获取起止日期
     * @param sdf 需要显示的日期格式
     * @param date 需要参照的日期
     * @param n 最近n周
     * @param option 0 开始日期;1 结束日期
     * @param k 0 包含本周 1 不包含本周
     * @return
     */
    public static String getFromToDate(SimpleDateFormat sdf, Date date, int n, int option, int k) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int offset = 0 == option ? 1 - dayOfWeek : 7 - dayOfWeek;
        int amount = 0 == option ? offset - (n - 1  + k) * 7 : offset - k * 7;
        calendar.add(Calendar.DATE, amount);
        return sdf.format(calendar.getTime());
    }
 
    /**
     * 根据当前日期获得最近n周的日期区间(包含本周)
     * @param n
     * @param sdf
     * @return
     */
    public static String getNWeekTimeInterval(int n, SimpleDateFormat sdf) {
        String beginDate = getFromToDate(sdf, new Date(), n, 0, 0);
        String endDate = getFromToDate(sdf, new Date(), n, 1, 0);
        return beginDate + "," + endDate;
    }
 
    /**
     * 根据当前日期获得最近n周的日期区间(不包含本周)
     * @param n
     * @param sdf
     * @return
     */
    public static String getNWeekTimeIntervalTwo(int n, SimpleDateFormat sdf) {
        String beginDate = getFromToDate(sdf, new Date(), n, 0, 1);
        String endDate = getFromToDate(sdf, new Date(), n, 1, 1);
        return beginDate + "," + endDate;
    }
 
    /**
     * 根据当前日期获得本周的日期区间(本周周一和周日日期)
     * @param sdf
     * @return
     */
    public static String getThisWeekTimeInterval(SimpleDateFormat sdf) {
        return getNWeekTimeInterval(1, sdf);
    }
 
    /**
     * 根据当前日期获得上周的日期区间(上周周一和周日日期)
     * @param sdf
     * @return
     */
    public static String getLastWeekTimeInterval(SimpleDateFormat sdf) {
        return getNWeekTimeIntervalTwo(1, sdf);
    }
 
    public static void main(String[] args) {
        System.out.println(getThisWeekTimeInterval(new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"))); // 获得本周的日期区间
        System.out.println(getLastWeekTimeInterval(new SimpleDateFormat("yyyy-MM-dd HH:ss:mm"))); // 获得上周的日期区间
    }
}

类二:

/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.cn.hnust.util;

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

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
 * @author ThinkGem
 * @version 2014-4-15
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
	
	private static String[] parsePatterns = {
		"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
		"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
		"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

	/**
	 * 得到当前日期字符串 格式(yyyy-MM-dd)
	 */
	public static String getDate() {
		return getDate("yyyy-MM-dd");
	}
	
	/**
	 * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String getDate(String pattern) {
		return DateFormatUtils.format(new Date(), pattern);
	}
	
	/**
	 * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
	 */
	public static String formatDate(Date date, Object... pattern) {
		String formatDate = null;
		if (pattern != null && pattern.length > 0) {
			formatDate = DateFormatUtils.format(date, pattern[0].toString());
		} else {
			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
		}
		return formatDate;
	}
	
	/**
	 * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
	 */
	public static String formatDateTime(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}
	
	/**
	 * 得到日期时间字符串,转换格式(yyyy年MM月dd日 HH:mm)
	 */
	public static String formatDate(Date date) {
		return formatDate(date, "yyyy年MM月dd日 HH:mm");
	}
	/**
	 * 得到日期时间字符串,转换格式(MM月dd日)
	 * @param date
	 * @return
	 */
	public static String formatMonthAndDay(Date date){
		return formatDate(date, "MM月dd日");
	}
	/**
	 * 得到当前时间字符串 格式(HH:mm:ss)
	 */
	public static String getTime() {
		return formatDate(new Date(), "HH:mm:ss");
	}

	/**
	 * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
	 */
	public static String getDateTime() {
		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 得到当前年份字符串 格式(yyyy)
	 */
	public static String getYear() {
		return formatDate(new Date(), "yyyy");
	}

	/**
	 * 得到当前月份字符串 格式(MM)
	 */
	public static String getMonth() {
		return formatDate(new Date(), "MM");
	}

	/**
	 * 得到当天字符串 格式(dd)
	 */
	public static String getDay() {
		return formatDate(new Date(), "dd");
	}

	/**
	 * 得到当前星期字符串 格式(E)星期几
	 */
	public static String getWeek() {
		return formatDate(new Date(), "E");
	}
	
	/**
	 * 日期型字符串转化为日期 格式
	 * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", 
	 *   "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
	 *   "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
	 */
	public static Date parseDate(Object str) {
		if (str == null){
			return null;
		}
		try {
			return parseDate(str.toString(), parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}

	public static Date parseDate(String str) {
		if (str == null){
			return null;
		}
		try {
			return parseDate(str, parsePatterns);
		} catch (ParseException e) {
			return null;
		}
	}
	/**
	 * 获取过去的天数
	 * @param date
	 * @return
	 */
	public static long pastDays(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(24*60*60*1000);
	}

	/**
	 * 获取过去的小时
	 * @param date
	 * @return
	 */
	public static long pastHour(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(60*60*1000);
	}
	
	/**
	 * 获取过去的分钟
	 * @param date
	 * @return
	 */
	public static long pastMinutes(Date date) {
		long t = new Date().getTime()-date.getTime();
		return t/(60*1000);
	}
	
	/**
	 * 转换为时间(天,时:分:秒.毫秒)
	 * @param timeMillis
	 * @return
	 */
    public static String formatDateTime(long timeMillis){
		long day = timeMillis/(24*60*60*1000);
		long hour = (timeMillis/(60*60*1000)-day*24);
		long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
		long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
		long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
		return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
    }
	
	/**
	 * 获取两个日期之间的天数
	 * 
	 * @param before
	 * @param after
	 * @return
	 */
	public static double getDistanceOfTwoDate(Date before, Date after) {
		long beforeTime = before.getTime();
		long afterTime = after.getTime();
		return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
	}
	
	/**
	 * 天数增加
	 */
	public static Date dateAdd(Date ptime,Integer day){
		String str = DatetoString(ptime, "yyyy-MM-dd");
		Date date = StringToDate(str, "yyyy-MM-dd");
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		ca.add(Calendar.DATE, day);// day为增加的天数,可以改变的
		date = ca.getTime();
		return date;
	}
	
	
	/**
	 * 日期增加(带时分秒)
	 */
	public static Date dateAddHms(Date ptime,Integer day){
		String str = DatetoString(ptime, "yyyy-MM-dd HH:mm:ss");
		Date date = StringToDate(str, "yyyy-MM-dd HH:mm:ss");
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		ca.add(Calendar.DATE, day);// day为增加的天数,可以改变的
		date = ca.getTime();
		return date;
	}
	
	/**
	 * 小时增加
	 */
	public static Date hourAdd(Date ptime,Integer hour){
		String str = DatetoString(ptime, "yyyy-MM-dd HH:mm:ss");
		Date date = StringToDate(str, "yyyy-MM-dd HH:mm:ss");
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		ca.add(Calendar.HOUR, hour);// hour为增加的小时,可以改变的
		date = ca.getTime();
		return date;
	}
	
	/**
	 * 获取特定时间的后一天凌晨0点的date
	 * 
	 */
	public static Date dateAddFormatYmdhms(Date ptime,Integer day){
		Date date=dateAdd(ptime,day);
		return dateymdhms(date);
	}
	
	/**
	 * date转String 
	 * @param date
	 * @return
	 */
	public static String DatetoString(Date date,String ymd){
		   SimpleDateFormat sdf = new SimpleDateFormat(ymd);
		   String str = sdf.format(date);
		return str;
	}
	
	/**
	 * String 转date
	 * @param str
	 * @param ymd
	 * @return
	 */
	public static Date StringToDate(String str,String ymd){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat(ymd);
		try {
			date = sdf.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}
	
	public static Date dateymd(Date ptime){
		String str = DatetoString(ptime,"yyyy-MM-dd");
		Date date = StringToDate(str, "yyyy-MM-dd");
		return date;
	}
	
	public static Date dateymdhms(Date ptime){
		String str = DatetoString(ptime,"yyyy-MM-dd HH:mm:ss");
		Date date = StringToDate(str, "yyyy-MM-dd HH:mm:ss");
		return date;
	}
	
	public static Date getDateymd(){
		Date ptime=new Date();
		String str = DatetoString(ptime,"yyyy-MM-dd");
		Date date = StringToDate(str, "yyyy-MM-dd");
		return date;
	}
	
	public static Date getDateymdhms(){
		Date ptime=new Date();
		String str = DatetoString(ptime,"yyyy-MM-dd HH:mm:ss");
		Date date = StringToDate(str, "yyyy-MM-dd HH:mm:ss");
		return date;
	}
	
	/**
	 * @param args
	 * @throws ParseException
	 */
	public static void main(String[] args) throws ParseException {
//		System.out.println(formatDate(parseDate("2010/3/6")));
//		System.out.println(getDate("yyyy年MM月dd日 E"));
//		long time = new Date().getTime()-parseDate("2012-11-19").getTime();
//		System.out.println(time/(24*60*60*1000));
	}
	/**
	 * 获取某个月的第一天与最后一天
	 * @param date
	 * @return
	 */
	public static Map<String, String> getDayOfMonth(Date date) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 0);
        Date theDate = calendar.getTime();
        
        //第一天
        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
        gcLast.setTime(theDate);
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        String day_first = df.format(gcLast.getTime());
        StringBuffer str = new StringBuffer().append(day_first).append(" 00:00:00");
        day_first = str.toString();
 
        //最后一天
        calendar.add(Calendar.MONTH, 1);    //加一个月
        calendar.set(Calendar.DATE, 1);        //设置为该月第一天
        calendar.add(Calendar.DATE, -1);    //再减一天即为上个月最后一天
        String day_last = df.format(calendar.getTime());
        StringBuffer endStr = new StringBuffer().append(day_last).append(" 23:59:59");
        day_last = endStr.toString();
 
        Map<String, String> map = new HashMap<String, String>();
        map.put("first", day_first);
        map.put("last", day_last);
        return map;
    }
	/**
	 * 获取某个星期的第一天与最后一天(第一天为周一 最后一天为周日)
	 * @param date
	 * @return
	 */
	public static Map<String, String> getDayOfWeek(Date date) { 
		Map<String, String> map = new HashMap<String, String>();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance(); 
		try { 
			cal.setTime(date); 
			cal.set(Calendar.DAY_OF_WEEK, 2); 
		} catch (Exception e) { 
			e.printStackTrace();
		} 
		Date theDate = cal.getTime();
		String day_first = df.format(theDate);
        StringBuffer str = new StringBuffer().append(day_first).append(" 00:00:00");
        day_first = str.toString();
		map.put("first", day_first);
		cal = Calendar.getInstance(); 
		try { 
			cal.setTime(date); 
			cal.set(Calendar.DAY_OF_WEEK, 1); 
			cal.set(Calendar.DATE, cal.get(Calendar.DATE) + 7); 
		} catch(Exception e) { 
			e.printStackTrace(); 
		} 
		theDate = cal.getTime();
		String day_last = df.format(theDate);
        str = new StringBuffer().append(day_last).append(" 23:59:59");
        day_last = str.toString();
		map.put("last", day_last);
		return map;
	}
}
0

评论区