日期格式工具

public class DateUtil {

    public static StringgetNowDate(){

        SimpleDateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

        return df.format(new Date());

    }

    public static DategetNowDateTwo(){

        Date date =new Date();

        return date;

    }

    private static String[]formats =new String[3];

    static {

        formats[0] ="yyyy-MM-dd";

        formats[1] ="yyyy/MM/dd";

        formats[2] ="yyyy.MM.dd";

    }

    /**

        * yyyyMMddHHmmss

        *

         * @return

    */

    public static StringgetNowDateByyyyyMMddHHmmss() {

        Date currentTime = Calendar.getInstance().getTime();

        SimpleDateFormat formatter =new SimpleDateFormat("yyyyMMddHHmmss");

        String dateString = formatter.format(currentTime);

        return dateString;

    }

    public static StringgetNowDateByyyyyMMddHHmmss(String date) {

        String dateString =null;

        if (EmptyUtil.isEmpty(date)) {

            return null;

        }

        SimpleDateFormat formart =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SimpleDateFormat formatter =new SimpleDateFormat("yyyyMMddHHmmss");

        try {

            dateString = formatter.format(formart.parse(date));

            System.out.println(dateString);

        }catch (ParseException e) {

            e.printStackTrace();

            dateString =null;

        }

            return dateString;

    }

    public static StringgetNowDateDay() {

        Date currentTime = Calendar.getInstance().getTime();

        SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd");

        String dateString = formatter.format(currentTime);

        return dateString;

    }

    /**

    * 判断是否为时间格式,支持‘-’,‘/’,‘.’

    *

    * @param dateStr

    * @return

    */

    public static boolean isDate(String dateStr) {

        SimpleDateFormat simple =null;

        for (String format :formats) {

            simple =new SimpleDateFormat(format);

            try {

                simple.parse(dateStr);

                return true;

            }catch (ParseException e) {

            }

        }

        return false;

      }

    /**

    * 把日期字符串格式化成日期类型

    *

    * @param dateStr

    * @param format

    * @return

    */

    public static Dateconvert2Date(String dateStr, String format) {

        SimpleDateFormat simple =new SimpleDateFormat(format);

        try {

            simple.setLenient(false);

            return simple.parse(dateStr);

        }catch (Exception e) {

            return null;

        }

    }

    /**

    * 把日期类型格式化成字符串

    *

    * @param date

    * @param format

    * @return

    */

    public static Stringconvert2String(Date date, String format) {

        SimpleDateFormat formater =new SimpleDateFormat(format);

        try {

            return formater.format(date);

        }catch (Exception e) {

            return null;

        }

    }

    /**

    * 转sql的time格式

    *

    * @param date

    * @return

    */

    public static java.sql.TimestampconvertSqlTime(Date date) {

        java.sql.Timestamp timestamp =new java.sql.Timestamp(date.getTime());

        return timestamp;

    }

    /**

    * 转sql的日期格式

    *

    * @param date

    * @return

    */

    public static java.sql.DateconvertSqlDate(Date date) {

        java.sql.Date Datetamp =new java.sql.Date(date.getTime());

        return Datetamp;

    }

    /**

    * 获取当前日期

    *

    * @param format

    * @return

    */

    public static StringgetCurrentDate(String format) {

        return new SimpleDateFormat(format).format(new Date());

    }

    /**

    * 获取时间戳

    *

    * @return

    */

    public static long getTimestamp() {

        return System.currentTimeMillis();

    }

    /**

    * 获取月份的天数

    *

    * @param year

    * @param month

    * @return

    */

    public static int getDaysOfMonth(int year, int month) {

        Calendar calendar = Calendar.getInstance();

        calendar.set(year, month -1, 1);

        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    }

    /**

    * 获取日期的年

    *

    * @param date

    * @return

    */

    public static int getYear(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        return calendar.get(Calendar.YEAR);

    }

    /**

    * 获取日期的月

    *

    * @param date

    * @return

    */

    public static int getMonth(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        return calendar.get(Calendar.MONTH) +1;

    }

    /**

    * 获取日期的日

    *

    * @param date

    * @return

    */

    public static int getDay(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        return calendar.get(Calendar.DATE);

    }

    /**

    * 获取日期的时

    *

    * @param date

    * @return

    */

    public static int getHour(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        return calendar.get(Calendar.HOUR);

    }

    /**

    * 获取日期的分种

    *

    * @param date

    * @return

    */

    public static int getMinute(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        return calendar.get(Calendar.MINUTE);

    }

    /**

    * 获取日期的秒

    *

    * @param date

    * @return

    */

    public static int getSecond(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        return calendar.get(Calendar.SECOND);

    }

    /**

    * 获取星期几

    *

    * @param date

    * @return

    */

    public static int getWeekDay(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

        return dayOfWeek -1;

    }

    /**

    * 获取哪一年共有多少周

    *

    * @param year

    * @return

    */

    public static int getMaxWeekNumOfYear(int year) {

        Calendar c =new GregorianCalendar();

        c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);

        return getWeekNumOfYear(c.getTime());

    }

    /**

    * 取得某天是一年中的多少周

    *

    * @param date

    * @return

    */

    public static int getWeekNumOfYear(Date date) {

        Calendar c =new GregorianCalendar();

        c.setFirstDayOfWeek(Calendar.MONDAY);

        c.setMinimalDaysInFirstWeek(7);

        c.setTime(date);

        return c.get(Calendar.WEEK_OF_YEAR);

    }

    /**

    * 取得某天所在周的第一天

    *

    * @param date

    * @return

    */

    public static DategetFirstDayOfWeek(Date date) {

        Calendar c =new GregorianCalendar();

        c.setFirstDayOfWeek(Calendar.MONDAY);

        c.setTime(date);

        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());

        return c.getTime();

    }

    /**

    * 取得某天所在周的最后一天

    *

    * @param date

    * @return

    */

    public static DategetLastDayOfWeek(Date date) {

        Calendar c =new GregorianCalendar();

        c.setFirstDayOfWeek(Calendar.MONDAY);

        c.setTime(date);

        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() +6);

        return c.getTime();

    }

    /**

    * 取得某年某周的第一天 对于交叉:2008-12-29到2009-01-04属于2008年的最后一周,2009-01-05为2009年第一周的第一天

    *

    * @param year

    * @param week

    * @return

    */

    public static DategetFirstDayOfWeek(int year, int week) {

        Calendar calFirst = Calendar.getInstance();

        calFirst.set(year, 0, 7);

        Date firstDate =getFirstDayOfWeek(calFirst.getTime());

        Calendar firstDateCal = Calendar.getInstance();

        firstDateCal.setTime(firstDate);

        Calendar c =new GregorianCalendar();

        c.set(Calendar.YEAR, year);

        c.set(Calendar.MONTH, Calendar.JANUARY);

        c.set(Calendar.DATE, firstDateCal.get(Calendar.DATE));

        Calendar cal = (GregorianCalendar) c.clone();

        cal.add(Calendar.DATE, (week -1) *7);

        firstDate =getFirstDayOfWeek(cal.getTime());

        return firstDate;

    }

    /**

    * 取得某年某周的最后一天 对于交叉:2008-12-29到2009-01-04属于2008年的最后一周, 2009-01-04为

    * 2008年最后一周的最后一天

    *

    * @param year

    * @param week

    * @return

    */

    public static DategetLastDayOfWeek(int year, int week) {

        Calendar calLast = Calendar.getInstance();

        calLast.set(year, 0, 7);

        Date firstDate =getLastDayOfWeek(calLast.getTime());

        Calendar firstDateCal = Calendar.getInstance();

        firstDateCal.setTime(firstDate);

        Calendar c =new GregorianCalendar();

        c.set(Calendar.YEAR, year);

        c.set(Calendar.MONTH, Calendar.JANUARY);

        c.set(Calendar.DATE, firstDateCal.get(Calendar.DATE));

        Calendar cal = (GregorianCalendar) c.clone();

        cal.add(Calendar.DATE, (week -1) *7);

        Date lastDate =getLastDayOfWeek(cal.getTime());

        return lastDate;

    }

    private static Dateadd(Date date, int calendarField, int amount) {

        if (date ==null) {

            throw new IllegalArgumentException("The date must not be null");

        }else {

            Calendar c = Calendar.getInstance();

            c.setTime(date);

            c.add(calendarField, amount);

            return c.getTime();

        }

    }

    /*

    * 1则代表的是对年份操作, 2是对月份操作, 3是对星期操作, 5是对日期操作, 11是对小时操作, 12是对分钟操作, 13是对秒操作,    * 14是对毫秒操作*/

    /**

    * 增加年

    *

    * @param date

    * @param amount

    * @return

    */

    public static DateaddYears(Date date, int amount) {

        return add(date, 1, amount);

    }

    /**

    * 增加月

    *

    * @param date

    * @param amount

    * @return

    */

    public static DateaddMonths(Date date, int amount) {

        return add(date, 2, amount);

    }

    /**

    * 增加周

    *

    * @param date

    * @param amount

    * @return

    */

    public static DateaddWeeks(Date date, int amount) {

        return add(date, 3, amount);

    }

    /**

    * 增加天

    *

    * @param date

    * @param amount

    * @return

    */

    public static DateaddDays(Date date, int amount) {

        return add(date, 5, amount);

    }

    /**

    * 增加时

    *

    * @param date

    * @param amount

    * @return

    */

    public static DateaddHours(Date date, int amount) {

        return add(date, 11, amount);

    }

    /**

    * 增加分

    *

    * @param date

    * @param amount

    * @return

    */

    public static DateaddMinutes(Date date, int amount) {

        return add(date, 12, amount);

    }

    /**

    * 增加秒

    *

    * @param date

    * @param amount

    * @return

    */

    public static DateaddSeconds(Date date, int amount) {

        return add(date, 13, amount);

    }

    /**

    * 增加毫秒

    *

    * @param date

    * @param amount

    * @return

    */

    public static DateaddMilliseconds(Date date, int amount) {

        return add(date, 14, amount);

    }

    /**

    * time差

    *

    * @param before

    * @param after

    * @return

    */

    public static long diffTimes(Date before, Date after) {

        return after.getTime() - before.getTime();

    }

    /**

    * 秒差

    *

    * @param before

    * @param after

    * @return

    */

    public static long diffSecond(Date before, Date after) {

        return (after.getTime() - before.getTime()) /1000;

    }

    /**

    * 毫秒差

    *

    * @param before

    * @param after

    * @return

    */

    public static long diffhaomiao(Date before, Date after) {

        return (after.getTime() - before.getTime());

    }

    /**

    * 分种差

    *

    * @param before

    * @param after

    * @return

    */

    public static int diffMinute(Date before, Date after) {

        return (int) (after.getTime() - before.getTime()) /1000 /60;

    }

    /**

    * 时差

    *

    * @param before

    * @param after

    * @return

    */

    public static int diffHour(Date before, Date after) {

        return (int) (after.getTime() - before.getTime()) /1000 /60 /60;

    }

    /**

    * 时差

    *

    * @param before

    * @param after

    * @return

    */

    public static double diffHourWithDouble(Date before, Date after) {

        return (double) (after.getTime() - before.getTime())/1000 /60 /60;

    }

    /**

    * 天数差

    *

    * @param before

    * @param after

    * @return

    */

    public static int diffDay(Date before, Date after) {

        return Integer.parseInt(String.valueOf(((after.getTime() - before.getTime()) /86400000)));

    }

    /**

    * 月差

    *

    * @param before

    * @param after

    * @return

    */

    public static int diffMonth(Date before, Date after) {

        int monthAll =0;

        int yearsX =diffYear(before, after);

        Calendar c1 = Calendar.getInstance();

        Calendar c2 = Calendar.getInstance();

        c1.setTime(before);

        c2.setTime(after);

        int monthsX = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);

        monthAll = yearsX *12 + monthsX;

        int daysX = c2.get(Calendar.DATE) - c1.get(Calendar.DATE);

        if (daysX >0) {

                monthAll = monthAll +1;

        }

        return monthAll;

    }

    /**

    * 年差

    *

    * @param before

    * @param after

    * @return

    */

    public static int diffYear(Date before, Date after) {

        return getYear(after) -getYear(before);

    }

    /**

    * 设置23:59:59

    *

    * @param date

    * @return

    */

    public static DatesetEndDay(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        calendar.set(Calendar.HOUR_OF_DAY, 23);

        calendar.set(Calendar.MINUTE, 59);

        calendar.set(Calendar.SECOND, 59);

        return calendar.getTime();

    }

    /**

    * 设置00:00:00

    *

    * @param date

    * @return

    */

    public static DatesetStartDay(Date date) {

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        calendar.set(Calendar.HOUR_OF_DAY, 00);

        calendar.set(Calendar.MINUTE, 00);

        calendar.set(Calendar.SECOND, 00);

        return calendar.getTime();

    }

    /**

    * 获取两个时间相差多少

    *

    * @param endDate

    * @param startDate

    * @return

    */

    public static IntegergetDatePoor(Date endDate, Date startDate) {

        long nd =1000 *24 *60 *60;

        long nh =1000 *60 *60;

        long nm =1000 *60;

        // long ns = 1000;

        // 获得两个时间的毫秒时间差异

        long diff = endDate.getTime() - startDate.getTime();

        // 计算差多少天

        long day = diff / nd;

        // 计算差多少小时

        long hour = diff % nd / nh;

        // 计算差多少分钟

        long min = diff % nd % nh / nm;

        // 计算差多少秒//输出结果

        // long sec = diff % nd % nh % nm / ns;

        String abc = day +"天" + hour +"小时" + min +"分钟";

        return Integer.parseInt(hour +"");

    }

    /**

    * 比较两个时间的大小

    * 1:date1>date2

    * -1: date1

    * 0: date1=date2

    *

    * @param DATE1

    * @param DATE2

    * @return

    */

    public static int compare_date(String DATE1, String DATE2) {

        DateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {

            Date dt1 = df.parse(DATE1);

            Date dt2 = df.parse(DATE2);

            if (dt1.getTime() > dt2.getTime()) {

                System.out.println("dt1>dt2");

                return 1;

            }else if (dt1.getTime() < dt2.getTime()) {

                System.out.println("dt1<dt2");

                return -1;

            }else {

                return 0;

            }

        }catch (Exception exception) {

            exception.printStackTrace();

        }

        return 0;

    }

    /**

    * @param nowDate  要比较的时间

    * @param startDate 开始时间

    * @param endDate  结束时间

    * @return true在时间段内,false不在时间段内

    * @throws Exception

    */

    public static boolean hourMinuteBetween(String nowDate, String startDate, String endDate)throws Exception {

        SimpleDateFormat format =new SimpleDateFormat("HH:mm:ss");

        Date now = format.parse(nowDate);

        Date start = format.parse(startDate);

        Date end = format.parse(endDate);

        long nowTime = now.getTime();

        long startTime = start.getTime();

        long endTime = end.getTime();

        return nowTime >= startTime && nowTime <= endTime;

    }

    /**

    * 比较

    *

    * @param date1

    * @param date2

    * @return

    */

    public static boolean timebetweenHours(String date1, String date2, long betweenNum){

    try{

            SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            return sdf.parse(date2).getTime() - sdf.parse(date1).getTime() <= betweenNum *60L *60L *1000L;

        }catch(Exception e){

            e.printStackTrace();

        }

            return false;

    }

    /**

    * 获取时间差

    * @return

    */

    public static StringgetDifferenceTime(Date start,Date end){

        long l =diffhaomiao(start, end);

        return l+"毫秒";

    }

    /**

    * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致

    *

    * @param nowTime 当前时间

    * @param startTime 开始时间

    * @param endTime 结束时间

    * @return

    * @author Another

*/

    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {

        if (nowTime.getTime() == startTime.getTime()

        || nowTime.getTime() == endTime.getTime()) {

            return true;

        }

        Calendar date = Calendar.getInstance();

        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();

        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();

        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {

            return true;

        }else {

            return false;

        }

    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,045评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,114评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,120评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,902评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,828评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,132评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,590评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,258评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,408评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,335评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,385评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,068评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,660评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,747评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,967评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,406评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,970评论 2 341