日期工具_踟蹰千年的博客-程序员秘密

技术标签: # 常用工具类  

各种常见日期需求基本涵盖

public class DateUtil {

    /**
     * Base ISO 8601 Date format yyyyMMdd i.e., 20021225 for the 25th day of December in the year 2002
     */
    public static final String ISO_DATE_FORMAT = "yyyyMMdd";

    /**
     * Expanded ISO 8601 Date format yyyy-MM-dd i.e., 2002-12-25 for the 25th day of December in the year 2002
     */
    public static final String ISO_EXPANDED_DATE_FORMAT = "yyyy-MM-dd";

    /**
     * yyyy-MM-dd hh:mm:ss
     */
    public static String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static String DATE_PATTERN = "yyyyMMddHHmmss";
   
    /**
     * 则个
     */
    private static boolean LENIENT_DATE = false;


    private static Random random = new Random();
    private static final int ID_BYTES = 10;

    public synchronized static String generateId() {
        StringBuffer result = new StringBuffer();
        result = result.append(System.currentTimeMillis());
        for (int i = 0; i < ID_BYTES; i++) {
            result = result.append(random.nextInt(10));
        }
        return result.toString();
    }

    protected static final float normalizedJulian(float JD) {

        float f = Math.round(JD + 0.5f) - 0.5f;

        return f;
    }

    /**
     * Returns the Date from a julian. The Julian date will be converted to noon GMT,
     * such that it matches the nearest half-integer (i.e., a julian date of 1.4 gets
     * changed to 1.5, and 0.9 gets changed to 0.5.)
     *
     * @param JD the Julian date
     * @return the Gregorian date
     */
    public static final Date toDate(float JD) {

        /* To convert a Julian Day Number to a Gregorian date, assume that it is for 0 hours, Greenwich time (so
         * that it ends in 0.5). Do the following calculations, again dropping the fractional part of all
         * multiplicatons and divisions. Note: This method will not give dates accurately on the
         * Gregorian Proleptic Calendar, i.e., the calendar you get by extending the Gregorian
         * calendar backwards to years earlier than 1582. using the Gregorian leap year
         * rules. In particular, the method fails if Y<400. */
        float Z = (normalizedJulian(JD)) + 0.5f;
        float W = (int) ((Z - 1867216.25f) / 36524.25f);
        float X = (int) (W / 4f);
        float A = Z + 1 + W - X;
        float B = A + 1524;
        float C = (int) ((B - 122.1) / 365.25);
        float D = (int) (365.25f * C);
        float E = (int) ((B - D) / 30.6001);
        float F = (int) (30.6001f * E);
        int day = (int) (B - D - F);
        int month = (int) (E - 1);

        if (month > 12) {
            month = month - 12;
        }

        int year = (int) (C - 4715); //(if Month is January or February) or C-4716 (otherwise)

        if (month > 2) {
            year--;
        }

        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1); // damn 0 offsets
        c.set(Calendar.DATE, day);

        return c.getTime();
    }

    /**
     * Returns the days between two dates. Positive values indicate that
     * the second date is after the first, and negative values indicate, well,
     * the opposite. Relying on specific times is problematic.
     *
     * @param early the "first date"
     * @param late the "second date"
     * @return the days between the two dates
     */
    public static final int daysBetween(Date early, Date late) {

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(early);
        c2.setTime(late);

        return daysBetween(c1, c2);
    }

    /**
     * Returns the days between two dates. Positive values indicate that
     * the second date is after the first, and negative values indicate, well,
     * the opposite.
     *
     * @param early
     * @param late
     * @return the days between two dates.
     */
    public static final int daysBetween(Calendar early, Calendar late) {

        return (int) (toJulian(late) - toJulian(early));
    }

    /**
     * Return a Julian date based on the input parameter. This is
     * based from calculations found at
     * <a href="http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html">Julian Day Calculations
     * (Gregorian Calendar)</a>, provided by Bill Jeffrys.
     * @param c a calendar instance
     * @return the julian day number
     */
    public static final float toJulian(Calendar c) {

        int Y = c.get(Calendar.YEAR);
        int M = c.get(Calendar.MONTH);
        int D = c.get(Calendar.DATE);
        int A = Y / 100;
        int B = A / 4;
        int C = 2 - A + B;
        float E = (int) (365.25f * (Y + 4716));
        float F = (int) (30.6001f * (M + 1));
        float JD = C + D + E + F - 1524.5f;

        return JD;
    }

    /**
     * Return a Julian date based on the input parameter. This is
     * based from calculations found at
     * <a href="http://quasar.as.utexas.edu/BillInfo/JulianDatesG.html">Julian Day Calculations
     * (Gregorian Calendar)</a>, provided by Bill Jeffrys.
     * @param date
     * @return the julian day number
     */
    public static final float toJulian(Date date) {

        Calendar c = Calendar.getInstance();
        c.setTime(date);

        return toJulian(c);
    }

    /**
     * @param isoString  
     * @param fmt 
     * @param field   Calendar.YEAR/Calendar.MONTH/Calendar.DATE
     * @param amount 
     * @return
     * @throws ParseException
     */
    public static final String dateIncrease(String isoString, String fmt,
                                            int field, int amount) {

        try {
            Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone(
                    "GMT"));
            cal.setTime(stringToDate(isoString, fmt, true));
            cal.add(field, amount);

            return dateToString(cal.getTime(), fmt);

        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * Time Field Rolling function.
     * Rolls (up/down) a single unit of time on the given time field.
     *
     * @param isoString
     * @param field the time field.
     * @param up Indicates if rolling up or rolling down the field value.
     * @param fmt use formating char's
     * @exception ParseException if an unknown field value is given.
     */
    public static final String roll(String isoString, String fmt, int field,
                                    boolean up) throws ParseException {

        Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone(
                "GMT"));
        cal.setTime(stringToDate(isoString, fmt));
        cal.roll(field, up);

        return dateToString(cal.getTime(), fmt);
    }

    /**
     * Time Field Rolling function.
     * Rolls (up/down) a single unit of time on the given time field.
     *
     * @param isoString
     * @param field the time field.
     * @param up Indicates if rolling up or rolling down the field value.
     * @exception ParseException if an unknown field value is given.
     */
    public static final String roll(String isoString, int field, boolean up) throws
            ParseException {

        return roll(isoString, DATETIME_PATTERN, field, up);
    }

    /**
     *  java.util.Date
     * @param dateText  
     * @param format  
     * @param lenient  
     * @return
     */
    public static Date stringToDate(String dateText, String format,
                                    boolean lenient) {

        if (dateText == null) {

            return null;
        }

        DateFormat df = null;

        try {

            if (format == null) {
                df = new SimpleDateFormat();
            } else {
                df = new SimpleDateFormat(format);
            }

            // setLenient avoids allowing dates like 9/32/2001
            // which would otherwise parse to 10/2/2001
            df.setLenient(false);

            return df.parse(dateText);
        } catch (ParseException e) {

            return null;
        }
    }

    /**
     * @return Timestamp
     */
    public static java.sql.Timestamp getCurrentTimestamp() {
        return new java.sql.Timestamp(new Date().getTime());
    }

    /** java.util.Date
     * @param dateString
     * @param format  
     * @return
     */
    public static Date stringToDate(String dateString, String format) {

        return stringToDate(dateString, format, LENIENT_DATE);
    }

    /**
     * java.util.Date
     * @param dateString
     */
    public static Date stringToDate(String dateString) {
        return stringToDate(dateString, ISO_EXPANDED_DATE_FORMAT, LENIENT_DATE);
    }

    /**  
     * @return 
     * @param pattern 
     * @param date  
     */
    public static String dateToString(Date date, String pattern) {

        if (date == null) {

            return null;
        }

        try {

            SimpleDateFormat sfDate = new SimpleDateFormat(pattern);
            sfDate.setLenient(false);

            return sfDate.format(date);
        } catch (Exception e) {

            return null;
        }
    }

    /**
     * yyyy-MM-dd
     * @param date
     * @return
     */
    public static String dateToString(Date date) {
        return dateToString(date, ISO_EXPANDED_DATE_FORMAT);
    }

    /**  
     * @return  
     */
    public static Date getCurrentDateTime() {
        Calendar calNow = Calendar.getInstance();
        Date dtNow = calNow.getTime();

        return dtNow;
    }

    /**
     *  
     * @param pattern  
     * @return
     */
    public static String getCurrentDateString(String pattern) {
        return dateToString(getCurrentDateTime(), pattern);
    }

    /**
     *   yyyy-MM-dd
     * @return
     */
    public static String getCurrentDateString() {
        return dateToString(getCurrentDateTime(), ISO_EXPANDED_DATE_FORMAT);
    }

    /**
     * 返回固定格式的当前时间
     *   yyyy-MM-dd hh:mm:ss
     * @param date
     * @return
     */
    public static String dateToStringWithTime( ) {

        return dateToString(new Date(), DATETIME_PATTERN);
    }

    
    /**
     *   yyyy-MM-dd hh:mm:ss
     * @param date
     * @return
     */
    public static String dateToStringWithTime(Date date) {

        return dateToString(date, DATETIME_PATTERN);
    }

    /**
     *  
     * @param date
     * @param days
     * @return java.util.Date
     */
    public static Date dateIncreaseByDay(Date date, int days) {

        Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone(
                "GMT"));
        cal.setTime(date);
        cal.add(Calendar.DATE, days);

        return cal.getTime();
    }

    /**
     *  
     * @param date
     * @param mnt
     * @return java.util.Date
     */
    public static Date dateIncreaseByMonth(Date date, int mnt) {

        Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone(
                "GMT"));
        cal.setTime(date);
        cal.add(Calendar.MONTH, mnt);

        return cal.getTime();
    }

    /**
     *  
     * @param date
     * @param mnt
     * @return java.util.Date
     */
    public static Date dateIncreaseByYear(Date date, int mnt) {

        Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone(
                "GMT"));
        cal.setTime(date);
        cal.add(Calendar.YEAR, mnt);

        return cal.getTime();
    }

    /**
     *  
     * @param date   yyyy-MM-dd
     * @param days
     * @return  yyyy-MM-dd
     */
    public static String dateIncreaseByDay(String date, int days) {
        return dateIncreaseByDay(date, ISO_DATE_FORMAT, days);
    }

    /**
     * @param date  
     * @param fmt  
     * @param days
     * @return
     */
    public static String dateIncreaseByDay(String date, String fmt, int days) {
        return dateIncrease(date, fmt, Calendar.DATE, days);
    }

    /**
     *  
     * @param src  
     * @param srcfmt  
     * @param desfmt 
     * @return
     */
    public static String stringToString(String src, String srcfmt,
                                        String desfmt) {
        return dateToString(stringToDate(src, srcfmt), desfmt);
    }

    /**
     *  
     * @param date  
     * @return string
     */
    public static String getYear(Date date) {
        SimpleDateFormat formater = new SimpleDateFormat(
                "yyyy");
        String cur_year = formater.format(date);
        return cur_year;
    }

    /**
     *  
     * @param date  
     * @return string
     */
    public static String getMonth(Date date) {
        SimpleDateFormat formater = new SimpleDateFormat(
                "MM");
        String cur_month = formater.format(date);
        return cur_month;
    }

    /**
     * @param date  
     * @return string
     */
    public static String getDay(Date date) {
        SimpleDateFormat formater = new SimpleDateFormat(
                "dd");
        String cur_day = formater.format(date);
        return cur_day;
    }
    
    public static int getDayInt(Date date) {
        SimpleDateFormat formater = new SimpleDateFormat(
                "dd");
        String cur_day = formater.format(date);
        return Integer.valueOf(cur_day);
    }
    
    /**
     * @param date  
     * @return string
     */
    public static String getHour(Date date) {
        SimpleDateFormat formater = new SimpleDateFormat(
                "HH");
        String cur_day = formater.format(date);
        return cur_day;
    }    

    public static int getMinsFromDate(Date dt) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(dt);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int min = cal.get(Calendar.MINUTE);
        return ((hour * 60) + min);
    }

    /**
     * Function to convert String to Date Object. If invalid input then current or next day date
     * is returned (Added by Ali Naqvi on 2006-5-16).
     * @param str String input in YYYY-MM-DD HH:MM[:SS] format.
     * @param isExpiry boolean if set and input string is invalid then next day date is returned
     * @return Date
     */
    public static Date convertToDate(String str, boolean isExpiry) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date dt = null;
        try {
            dt = fmt.parse(str);
        } catch (ParseException ex) {
            Calendar cal = Calendar.getInstance();
            if (isExpiry) {
                cal.add(Calendar.DAY_OF_MONTH, 1);
                cal.set(Calendar.HOUR_OF_DAY, 23);
                cal.set(Calendar.MINUTE, 59);
            } else {
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
            }
            dt = cal.getTime();
        }
        return dt;
    }

    public static Date convertToDate(String str) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Date dt = null;
        try {
            dt = fmt.parse(str);
        } catch (ParseException ex) {
            dt = new Date();
        }
        return dt;
    }

    public static String dateFromat(Date date, int minute) {
        String dateFormat = null;
        int year = Integer.parseInt(getYear(date));
        int month = Integer.parseInt(getMonth(date));
        int day = Integer.parseInt(getDay(date));
        int hour = minute / 60;
        int min = minute % 60;
        dateFormat = String.valueOf(year)
                     +
                     (month > 9 ? String.valueOf(month) :
                      "0" + String.valueOf(month))
                     +
                     (day > 9 ? String.valueOf(day) : "0" + String.valueOf(day))
                     + " "
                     +
                     (hour > 9 ? String.valueOf(hour) : "0" + String.valueOf(hour))
                     +
                     (min > 9 ? String.valueOf(min) : "0" + String.valueOf(min))
                     + "00";
        return dateFormat;
    }
    
    public static String sDateFormat() {
    	return new SimpleDateFormat(DATE_PATTERN).format(Calendar.getInstance().getTime());	
    }
    
    /**
     * 
     * @Description: 获得本月的第一天日期
     * @return
     * 
     * @author leechenxiang
     * @date 2017年5月31日 下午1:37:34
     */
    public static String getFirstDateOfThisMonth() {
    	
    	SimpleDateFormat format = new SimpleDateFormat(ISO_EXPANDED_DATE_FORMAT);
		
		Calendar calendarFirst = Calendar.getInstance();
		calendarFirst = Calendar.getInstance();  
        calendarFirst.add(Calendar.MONTH, 0);  
        calendarFirst.set(Calendar.DAY_OF_MONTH, 1);  
        String firstDate = format.format(calendarFirst.getTime()); 
        
        return firstDate;
    }
    
    /**
     * 
     * @Description: 获得本月的最后一天日期
     * @return
     * 
     * @author leechenxiang
     * @date 2017年5月31日 下午1:37:50
     */
    public static String getLastDateOfThisMonth() {
    	SimpleDateFormat format = new SimpleDateFormat(ISO_EXPANDED_DATE_FORMAT);  
		
		Calendar calendarLast = Calendar.getInstance();
		calendarLast.setTime(new Date());
		calendarLast.getActualMaximum(Calendar.DAY_OF_MONTH);
		
		String lastDate = format.format(calendarLast.getTime());  
		return lastDate;
    }
    
    /**
     * @Description: 判断字符串日期是否匹配指定的格式化日期
     */
	public static boolean isValidDate(String strDate, String formatter) {
		SimpleDateFormat sdf = null;
		ParsePosition pos = new ParsePosition(0);

		if (StringUtils.isBlank(strDate) || StringUtils.isBlank(formatter)) {
			return false;
		}
		try {
			sdf = new SimpleDateFormat(formatter);
			sdf.setLenient(false);
			Date date = sdf.parse(strDate, pos);
			if (date == null) {
				return false;
			} else {
				if (pos.getIndex() > sdf.format(date).length()) {
					return false;
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
    
    public static void main(String[] args)
	{
//    	String timeDir=DateUtil.dateToString(new Date(),DateUtil.ISO_EXPANDED_DATE_FORMAT);
//		System.out.println(timeDir);
    	boolean flag = DateUtil.isValidDate("1990-10-32", DateUtil.ISO_EXPANDED_DATE_FORMAT);
    	System.out.println(flag);
	}
    
}

 

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/baiyan3212/article/details/104450299

智能推荐

阶段3 3.SpringMVC·_07.SSM整合案例_08.ssm整合之Spring整合MyBatis框架_weixin_30566063的博客-程序员秘密

service能供成功的调用到service对象就算是整合成功如果能把生成的代理对象也存大IOC的容器中。那么ServiceImpl就可以拿到这个对象 做一个注入,然后就可以调用代理对象的查询数据库的方法核心的问题就是把代理对象存在IOC的容器中在applicationContext.xml工程可以帮我们创建session。有了session就可以拿...

Qt中十六进制的QString字符串转换成十六进制数的方法_16进制字符串转16进制数 qt_Veiko的博客-程序员秘密

在之前错误地以为QString::toInt只能转换成十进制整数,因此在QString的十六进制字符串转成十进制花了一些心思,专门写了一些类似QString_to_hex的函数来进行这些转换,相信以后不会再犯这种错误了,下面这个函数为例说明Qt中QString::toInt用于字符串转十六进制数的方法:/*****************************************

Unity基础篇:画布的相机渲染模式_unity相机渲染_Peter_Gao_的博客-程序员秘密

一、Canvas简介  Canvas画布是承载所有UI元素的区域。Canvas实际上是一个游戏对象上绑定了Canvas组件。所有的UI元素都必须是Canvas的自对象。如果场景中没有画布,那么我们创建任何一个UI元素,都会自动创建画布,并且将新元素置于其下。二、创建画布  当你创建任何一个UI元素的时候,都会自动创建画布。也可以主动创建一张画布:点击GameObject-&gt;UI-&gt;Canvas即可在Hierarchy面板创建一张画布。三、画布参数:RenderMode渲染

灵性图书馆:好书推荐-《觉悟自我的科学》_觉悟自我的科学 书评_vx_xuelingxing666的博客-程序员秘密

编辑推荐:本书深度探索有关内在自我、自然、宇宙以及内外超然自我的奥秘。在自我觉悟的科学方面杰出的世界大师在这里谈到了现代的瑜伽冥想修行、业报定律的摆脱、超然知觉的获得等等。内容简介:本书深度探索有关内在自我、自然、宇宙以及内外超然自我的奥秘。在自我觉悟的科学方面最杰出的世界大师在这里谈到了现代的瑜伽冥想修行、业报定律的摆脱、超然知觉的获得等等。本书选录了圣哲帕布帕德与各科学家、医学家等人士的信件交流,以及各类采访、讲座、文章,从中展现出A.C.巴克提维丹塔.斯瓦米.帕布帕德在言谈中所蕴藏的智慧与力量。他证实

Windows下使用Jenkins进行Spring Boot项目自动打包运行_yangjinping_c的博客-程序员秘密

至于介绍和安装这里就多说了网上很多,这里我只说下使用1.首先配置全局环境变量2.点击创建新任务,设置项目放弃前面5次的构建,节省空间3.设置源码管理 设置git路径,以及用户密码 4.创建构建触发器因为我在本机,不能设置提交代码后推送,要想设置的自行百度怎么设置webhooks,这里我设置轮询5分钟检查一次代码有没有提交,有提交自动构建,没有就不构建...

mongodb linux 安装包,MongoDB之Linux通用二进制包安装_力力nevergg的博客-程序员秘密

MongoDB是开源文档数据库,提供共性能、高可用、自动扩展等。MongoDB中记录是文档,其是字段和值组成的对结构。MongoDB文档类似JSON对象,字段的值可以包含其它文档、数组、文档的数组。记录组织成collection,相当于表。参考下图:使用文档的优点是:文档对应很多编程语言的内生数据对象内嵌文档和数组减少了join的开销动态schema支持顺畅多态关键功能:高性能:mongodb提供...

随便推点

appium操作介绍_appium remote_晒不黑的黑煤球的博客-程序员秘密

1.获取driver属性current_package:获取包名 current_activity:获取当前活动页面 ==&gt;url context:上下文web窗口切换,H5测试获取上下文 driver.switch_to.context contexts:所有的上下文 ==&gt;window_handers current_context:获取现在的上下文 获取当前窗口current_window_hander page_source:获取源码 XML capabilitie...

前端用layui分页后台做处理时进行手动配置pageInfo参数_layuipageinfo_不吃鱼的胖橘的博客-程序员秘密

做项目时遇到的需求,需要对多条select进行分页处理。将所有的查询结果list放到一起public PageDataResult getFollowUpList(Integer pageNum, Integer pageSize, String pid) { PageDataResult pageDataResult = new PageDataResult(); // 获取用户信息 Subject subject = SecurityUtils.

《CCIE路由和交换认证考试指南(第5版) (第2卷)》——1.3节构建BGP表_weixin_33884611的博客-程序员秘密

本节书摘来自异步社区《CCIE路由和交换认证考试指南(第5版) (第2卷)》一书中的第1章,第1.3节构建BGP表,作者 【美】那比克 科查理安(Narbik Kocharians) , 特里 文森(Terry Vinson) , 瑞克 格拉齐亚尼(Rick Graziani),更多章节内容可以访问云栖社区“异步社区”公众号查看1.3 构建BGP表BG...

python程序打包_Python代码的打包与发布详解_weixin_39568133的博客-程序员秘密

在python程序中,一个.py文件被当作一个模块,在各个模块中定义了不同的函数。当我们要使用某一个模块中的某一个函数时,首先须将这个模块导入,否则就会出现函数未定义的情况.下面记录的是打包及安装包的方法。本文示例是建立一个模拟登录的程序:logIn.py文件代码如下:pwd=int(raw_input('please input your passward: '))if pwd==123:pri...

ex1-linearRegression_Aaron_Liu0730的博客-程序员秘密

练习1:线性回归介绍在本练习中,您将 实现线性回归并了解其在数据上的工作原理。在开始练习前,需要下载如下的文件进行数据上传:ex1data1.txt -单变量的线性回归数据集 ex1data2.txt -多变量的线性回归数据集在整个练习中,涉及如下的必做作业,及标号*的选做作业:实现简单示例函数----------(5分) 实现数据集显示的函数-------(5分) 计算线性回归成本的函数-----(40分) 运行梯度下降的功能函数-----(50分) 数据标准化* 多变量

springboot部署jar包与依赖包分离至lib文件夹_springboot pom依赖和lib目录_x_san3的博客-程序员秘密

说明springboot构建jar部署,通过使用 java -jar xxx.jar 命令启动服务,非常方便,但是通过maven构建的jar包含 \BOOT-INF\lib\下的所有依赖jar包,导致jar包文件太大,本文将接解决这一问题。解决思路在maven构建springboot项目jar时候,将lib文件夹分离出来。在运行jar的时候,能够应用到分离的lib包。解决步骤...

推荐文章

热门文章

相关标签