关闭

超级全的时间处理工具类(格式化,精确,以及自己定制)

标签: java格式化datastring工具
656人阅读 评论(0) 收藏 举报
分类:
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang.time.DateUtils;
/* humf */
public class DateUtil {
	public static final String YYYY_MM_DD = "yyyy-MM-dd";
	public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
	public static final String YYYY_MMDD = "yyyyMMdd";
	public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	public static final String YYYY = "yyyy";
	public static final String YYYY_MM = "yyyyMM";

	private final static SimpleDateFormat dateformater = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
	private final static SimpleDateFormat dateformater1 = new SimpleDateFormat(YYYY_MM_DD);
	private final static SimpleDateFormat dateformater2 = new SimpleDateFormat(YYYY_MMDD);
	private final static SimpleDateFormat dateformater3 = new SimpleDateFormat(YYYYMMDDHHMMSS);
	private final static SimpleDateFormat dateformater4 = new SimpleDateFormat(YYYY_MM);
	private final static SimpleDateFormat dateformater5 = new SimpleDateFormat(YYYY);
	public static boolean defaultTimeFlag = true; 
	
	public final static String startTimePoint = " 00:00:00";
	public final static String endTimePoint = " 23:59:59";
	

	/**
	 * Format(yyyy_MM_dd HH:mm:ss)
	 * @return java.util.Date
	 */
	public static Date getNowDate() {
		Date date = null;
		try {
			date = parseUtilDate(dateformater.format(new Date()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}
    /**
     * 精确到时分秒
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static java.lang.String formatSecondDate(Date d) throws ParseException {
        return dateformater3.format(d);
    }
	public static String getFormatNowDay() {   
	    return dateformater1.format(new Date());   
	}  

	public static String getSNowDay() {   
	    return dateformater.format(new Date());   
	}  
	public static String getFormatDay(Date d) {   
	    return dateformater2.format(d);   
	}  
	
	public static String getMonthFirstDay() {   
	    Calendar calendar = Calendar.getInstance();   
	    calendar.set(Calendar.DAY_OF_MONTH, calendar   
	            .getActualMinimum(Calendar.DAY_OF_MONTH));
	    
	    return dateformater1.format(calendar.getTime());   
	}   
	  
	public static String getMonthLastDay() {   
	    Calendar calendar = Calendar.getInstance();   
	    calendar.set(Calendar.DAY_OF_MONTH, calendar   
	            .getActualMaximum(Calendar.DAY_OF_MONTH));   
	    return dateformater1.format(calendar.getTime());   
	}


    private final static long DAY_IN_MILLISECOND = 1000 * 3600 * 24;

    public final static long DAY_IN_SECOND = 3600 * 24;


    private DateUtil() {
    }

    public static java.util.Date getDate(java.util.Date startDate, int days) {
        java.util.Date returnDay = dateDayAdd(startDate, days);
        return returnDay;
    }

    public static java.util.Date getMonthDate(java.util.Date startDate,
                                              int months) {
        java.util.Date returnDay = dateMonthAdd(startDate, months);
        return returnDay;
    }

    public static String getCurMonth() {
        return new SimpleDateFormat("yyyy-MM").format(new java.util.Date());
    }

    public static java.util.Date getMonthBegin(java.util.Date month) {
        GregorianCalendar ca = new GregorianCalendar();
        ca.setTime(month);
        int year = ca.get(GregorianCalendar.YEAR);
        int mon = ca.get(GregorianCalendar.MONTH);
        GregorianCalendar gCal = new GregorianCalendar(year, mon, 1);
        return gCal.getTime();
    }

    public static java.util.Date getMonthBegin(int year, int month) {
        if (month <= 0 || month > 12)
            throw new IllegalArgumentException("month must from 1 to 12");
        GregorianCalendar gCal = new GregorianCalendar(year, month - 1, 1);
        return gCal.getTime();
    }
    public static java.util.Date getMonthEnd(java.util.Date month) {
        GregorianCalendar ca = new GregorianCalendar();
        ca.setTime(month);
        int year = ca.get(GregorianCalendar.YEAR);
        int mon = ca.get(GregorianCalendar.MONTH);
        int lastDay = ca.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
        GregorianCalendar gCal = new GregorianCalendar(year, mon, lastDay);
        return gCal.getTime();
    }

    public static java.util.Date getMonthEnd(int year, int month) {
        java.util.Date start = getMonthBegin(year, month);
        return getMonthEnd(start);
    }

    public static java.util.Date getWeekBegin(java.util.Date date) {
        GregorianCalendar gCal = new GregorianCalendar();
        gCal.setTime(date);
        int startDay = gCal.getActualMinimum(GregorianCalendar.DAY_OF_WEEK);
        gCal.set(GregorianCalendar.DAY_OF_WEEK, startDay);
        return gCal.getTime();
    }

    public static java.util.Date getWeekEnd(java.util.Date date) {
        GregorianCalendar gCal = new GregorianCalendar();
        gCal.setTime(date);
        int lastDay = gCal.getActualMaximum(GregorianCalendar.DAY_OF_WEEK);
        gCal.set(GregorianCalendar.DAY_OF_WEEK, lastDay);
        return gCal.getTime();
    }

    public static int getDays(java.sql.Timestamp beginTime,
                              java.sql.Timestamp endTime) {
        int days = (int) ((endTime.getTime() - beginTime.getTime()) / DAY_IN_MILLISECOND);
        return days;
    }

    public static java.sql.Date parseSqlDate(String strDate) {
        return java.sql.Date.valueOf(strDate);
    }

    /**
     * 精确到时分秒
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static java.util.Date parseUtilDate(String strDate) throws ParseException {
        return dateformater.parse(strDate);
    }

    /**
     * 精确到日
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static java.util.Date parseDayDate(String strDate) throws ParseException {
        return dateformater1.parse(strDate);
    }

    /**
     * 精确到日
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static java.util.Date parseDay2Date(String strDate) throws ParseException {
        return dateformater2.parse(strDate);
    }
    /**
     * 格式化时间
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static java.util.Date parse2Date(String strDate) throws ParseException {
    	java.util.Date d = null;
    	try {
			d =dateformater2.parse(strDate);
		} catch (Exception e) {
			try {
				d = dateformater4.parse(strDate);
			} catch (Exception e1) {
				d = dateformater5.parse(strDate);
			}
		}
        return d;
    } 
/**
 * 格式化时间
 * @param strDate
 * @return
 * @throws ParseException
 */
public static java.lang.String format2Date(Date date) throws ParseException {
	java.lang.String d = null;
	try {
		d =dateformater2.format(date);
	} catch (Exception e) {
		try {
			d = dateformater4.format(date);
		} catch (Exception e1) {
			d = dateformater5.format(date);
		}
	}
    return d;
}
    
    /**
     * 精确到日
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static java.lang.String formatDayDate(Date d) throws ParseException {
        return dateformater1.format(d);
    }

    /**
     * 精确到日
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static java.lang.String formatDate(Date d) throws ParseException {
        return dateformater2.format(d);
    }

    public static java.util.Date parseLastMonthDate() {
    	GregorianCalendar gCal = new GregorianCalendar();
        gCal.setTime(new Date());
        gCal.add(GregorianCalendar.MONTH, -1);
        return gCal.getTime();
    }
    public static java.sql.Timestamp parseLastMonthTimestamp() {
    	GregorianCalendar gCal = new GregorianCalendar();
        gCal.setTime(new Date());
        gCal.add(GregorianCalendar.MONTH, -1);
        return new java.sql.Timestamp(gCal.getTime().getTime());
    }

    public static java.sql.Timestamp getNextTimestamp(Timestamp e,int i) {
    	if(e==null) return new java.sql.Timestamp(new Date().getTime());
    	GregorianCalendar gCal = new GregorianCalendar();
        gCal.setTime(new Date(e.getTime()+i*1000*60*60*24));
        return new java.sql.Timestamp(gCal.getTime().getTime());
    }

    private static java.util.Date dateDayAdd(java.util.Date date, int days) {
        long now = date.getTime() + days * DAY_IN_MILLISECOND;
        return (new java.util.Date(now));
    }

    @SuppressWarnings("unused")
	private static java.sql.Timestamp dateDateTimeAdd(
            java.sql.Timestamp timestamp, int minutes) {
        long now = timestamp.getTime() + minutes * 1000 * 60;
        return (new java.sql.Timestamp(now));
    }
    
    public static long getDiffMinu(Timestamp startDate, Timestamp endDate) {
        long startTime = startDate.getTime();
        long endTime = endDate.getTime();
        System.out.println(startTime);
        System.out.println(endTime);

        long minu = (long) ((endTime - startTime) / (1000 * 60));
        return minu;
    }

    private static java.util.Date dateMonthAdd(java.util.Date date, int months) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        int m = cal.get(GregorianCalendar.MONTH) + months;
        if (m < 0)
            m += -12;
        cal.roll(GregorianCalendar.YEAR, m / 12);
        cal.roll(GregorianCalendar.MONTH, months);
        return cal.getTime();
    }

    @SuppressWarnings("unused")
	private static String getDateTimeStr(String str) {
        if (str.indexOf(" ") == -1)
            str += "  00:00:00";
        else if (str.lastIndexOf(":") == 13)
            str += ":00";
        return str;
    }

    public static int GetDaysOfMonth(int iYear, int Month) {
        int days = 0;
        switch (Month) {
            case 1:
                days = 31;
                break;
            case 2:
                if (IsRuYear(iYear)) {
                    days = 29;
                } else {
                    days = 28;
                }

                break;
            case 3:
                days = 31;
                break;
            case 4:
                days = 30;
                break;
            case 5:
                days = 31;
                break;
            case 6:
                days = 30;
                break;
            case 7:
                days = 31;
                break;
            case 8:
                days = 31;
                break;
            case 9:
                days = 30;
                break;
            case 10:
                days = 31;
                break;
            case 11:
                days = 30;
                break;
            case 12:
                days = 31;
                break;
        }

        return days;


    }

    private static boolean IsRuYear(int year) {

        if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
            return true;
        } else {
            return false;
        }
    }

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
        Calendar cal = Calendar.getInstance();

        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) w = 0;
        return weekDays[w];

    }

    public static String convertDateFormat(Date date, String format) {
        String time = "";
        try {
            time = (new SimpleDateFormat(format)).format(date);
        } catch (RuntimeException e) {
           
        }
        return time;
    }



    public static Date getDateFromSeconds(long seconds) {
        Calendar ca = Calendar.getInstance();
        ca.setTimeInMillis(seconds * 1000);
        return ca.getTime();
    }

    public static long getSecondsFromDurTime(String duration) {
        long seconds = 0;
        String[] dur = duration.split(":");
        seconds = new Long(dur[0]).longValue() * 3600 + new Long(dur[1]).longValue() * 60 + new Long(dur[2]).longValue();
        return seconds;
    }

    public static String formatDurTime(long durLong, String formatStr) {
        String durTime = "";
        if (formatStr == null || "".equals(formatStr))
            formatStr = "hh:mm:ss";
        String[] fmtArray = formatStr.split(":");
        for (int i = 0; i < fmtArray.length; i++) {
            if (fmtArray[i].equals("hh") || fmtArray[i].endsWith("小时")) {
                long hl = durLong / 3600;
                if (hl == 0)
                    continue;
                durLong = durLong % 3600;
                if (fmtArray[i].endsWith("小时"))
                    durTime += hl + fmtArray[i];
                else
                    durTime += hl + ":";
            } else if (fmtArray[i].equals("mm") || fmtArray[i].startsWith("分")) {
                long ml = durLong / 60;
                durLong = durLong % 60;
                if (fmtArray[i].startsWith("分"))
                    durTime += ml + fmtArray[i];
                else
                    durTime += ml + ":";
            } else if (fmtArray[i].equals("ss") || fmtArray[i].equals("秒")) {
                long sl = durLong;
                if (fmtArray[i].equals("秒"))
                    durTime += sl + "秒";
                else
                    durTime += sl;
            }
        }


        return durTime;
    }

    public static Date getFinallyDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        String fm = format.format(date);
        fm += " 23:59:59";
        try {
            return DateUtils.parseDate(fm, new String[] { "yyyyMMdd HH:mm:ss" });
        }
        catch (ParseException e1) {
            return null;
        }
    }

    public static Date getStartDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        String fm = format.format(date);
        fm += " 00:00:00";
        try {
            return DateUtils.parseDate(fm, new String[] { "yyyyMMdd HH:mm:ss" });
        }
        catch (ParseException e1) {
            return null;
        }
    }

    public static void main(String[] args) {
    	System.out.println(DateUtil.getDate(getNowDate(),3));
    } 
    /**
     * 
     * @param date ForExample:"20121221"
     * @param pattern ForExample:"yyyyMMdd"
     * @return
     */
    public static Date dateStringToDate(String date, String pattern){
    	DateFormat df = new SimpleDateFormat(pattern);
        Date today = null;
		try {
			today = df.parse(date);
		}catch (NullPointerException e){
			today = null;
		} catch (ParseException e) {
			today = null;
		}
        return today;
    }
    /**
	 * 给指定的日期加上天数 如:2008-2-27;加上10天则返回:2008-3-8
	 * 
	 * @param dDate
	 * @param iNbDay
	 * @return
	 */
	public static Date addDay(Date dDate, long iNbDay) {
		return addHour(dDate, iNbDay * 24);
	}
    /**
	 * 给指定的日期加上hour个小时.
	 * 
	 * @param dDate
	 *            指定的日期
	 * @param hour
	 *            几个小时
	 * @return 返回加完小时之后 的日期
	 */
	public static Date addHour(Date dDate, long hour) {
		return addSecond(dDate, hour * 60L * 60L);
	}
	
	/**
	 * 给指定的日期加上second秒
	 * 
	 * @param dDate
	 * @param second
	 * @return
	 */
	public static Date addSecond(Date dDate, long second) {

		long datems = dDate.getTime();
		long secondms = second * 1000L;
		long newDateMs = datems + secondms;
		Date result = new Date(newDateMs);
		return result;

	}
	/**
	 * 
	 */
	public static String getDateStr(String rource,String pattern,String format){
		   if(rource != null && !"".equals(rource)){
			   SimpleDateFormat df = new SimpleDateFormat(pattern);
				Date date = null;
				try {
					date = df.parse(rource);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				if(date != null){
					SimpleDateFormat df2 = new SimpleDateFormat(format);
					return df2.format(date);
				}else{
					return "";
				}			
		   }else{
			   return "";
		   }
		  
	   }
}

0
0
查看评论

定制自己的工具类-以输出函数(Print)为例

问题:在程序中调用System.out.println()嫌太长,想封装System.out.println()函数成为类Print的一个静态方法print,简化以后的调用
  • zpcandzhj
  • zpcandzhj
  • 2014-04-10 12:31
  • 1316

定制自己的java工具类

在java语言学习的过程中,我们可以创建自己的工具库来减少或消除重复的程序代码。 比如说我们可以用我们自己构建的类Print来代替System.out.print()以减少输入负担。 首先创建一个项目*******.util;然后在项目下新建一个名为org.print的包;在包内新建Print...
  • haiyoung
  • haiyoung
  • 2015-08-14 15:12
  • 1598

Java开发时间处理工具类(全)

java开发过程中常用的一些事件处理工具类
  • zhx19920405
  • zhx19920405
  • 2017-07-06 11:27
  • 243

时间处理工具类(DateUtil)

package com.lvmama.comm.utils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util...
  • jakeswang
  • jakeswang
  • 2016-06-23 15:38
  • 2097

定制自己的工具类

定制自己的打印信息类,方便调试,代码如下:        package dyk.viewpagerdemo.Log; import android.util.Log; /** * Created by Administrator on 2017/04/...
  • Look19
  • Look19
  • 2017-05-02 20:58
  • 121

时间处理工具类,和使用字符串或者日期处理需要注意的问题

数据库是DateTime类型 项目开发中:对时间的使用出现两种方式: 1.使用字符串来表示时间 2.使用Date来表示时间 1.先说说第一种方式会出现的问题:数据从后台传递到后台显示的时候不会有问题出现,但是如果前台提交数据,这个数据不是时间格式的数据的时候,不填的时候,在spring mvc中...
  • shenbushen
  • shenbushen
  • 2016-11-04 17:57
  • 739

java处理日期工具类(一)

package util; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import ja...
  • qq_17555933
  • qq_17555933
  • 2016-06-23 17:28
  • 3832

Java-如何定制自己的工具库: mytools or myutil

掌握了包的知识后,就可以创建自己的工具库来减少或消除重复的程序代码了。例如:给System.out.println()创建一个别名来减少输入负担。package edu.foresthe.mytools;public class P {     &#...
  • ForWayfarer
  • ForWayfarer
  • 2008-04-18 11:34
  • 1864

Maven超级POM

Maven有一个超级POM,所有的POM均继承此文件。你可以使用解压工具打开jar文件$M2_HOME/lib/maven-model-builder-x.x.x.jar,然后访问路径org/apache/maven/model/pom-4.0.0.xomPs: maven2中为org/apache...
  • wangmuming
  • wangmuming
  • 2015-07-16 17:56
  • 1291

BigDecimal、DecimalFormat工具类-浮点类型计算格式化-史上最全=_=

即上一篇屌的一批的时间操作工具类之后又一力作BigDecimal浮点类型操作/DecimalFormat浮点类型格式化保留小数注意:1. 强制依赖jdk8以上 2.方法:支持可变长参数,所有数值类型以及collection类型声明:可变长参数的方法跟传入两个参数的方法其实是可以用重载来声明相同的方法...
  • Hatsune_Miku_
  • Hatsune_Miku_
  • 2017-11-26 00:20
  • 260
    个人资料
    • 访问:74487次
    • 积分:1457
    • 等级:
    • 排名:千里之外
    • 原创:61篇
    • 转载:3篇
    • 译文:5篇
    • 评论:15条
    欢迎关注


    博客专栏
    技术交流和分享
    工作邮箱:humf@vip.qq.com
    技术分享和交流QQ群:432135803
    微信公众号
    微信公众号
    分享到: 微信 更多
    2