Java時(shí)間工具類Date的常用處理方法
前言
Date 類
Date 類表示系統(tǒng)特定的時(shí)間戳,可以精確到毫秒。Date 對(duì)象表示時(shí)間的默認(rèn)順序是星期、月、日、小時(shí)、分、秒、年。
構(gòu)造方法
Date 類有如下兩個(gè)構(gòu)造方法。
Date():此種形式表示分配 Date 對(duì)象并初始化此對(duì)象,以表示分配它的時(shí)間(精確到毫秒),使用該構(gòu)造方法創(chuàng)建的對(duì)象可以獲取本地的當(dāng)前時(shí)間。
Date(long date):此種形式表示從 GMT 時(shí)間(格林尼治時(shí)間)1970 年 1 月 1 日 0 時(shí) 0 分 0 秒開(kāi)始經(jīng)過(guò)參數(shù) date 指定的毫秒數(shù)。
這兩個(gè)構(gòu)造方法的使用示例如下:
Date date1 = new Date(); // 調(diào)用無(wú)參數(shù)構(gòu)造函數(shù) System.out.println(date1.toString()); // 輸出:Wed May 18 21:24:40 CST 2016 Date date2 = new Date(60000); // 調(diào)用含有一個(gè)long類型參數(shù)的構(gòu)造函數(shù) System.out.println(date2); // 輸出:Thu Jan 0108:01:00 CST 1970
Date 類的無(wú)參數(shù)構(gòu)造方法獲取的是系統(tǒng)當(dāng)前的時(shí)間,顯示的順序?yàn)樾瞧?、月、日、小時(shí)、分、秒、年。
Date 類帶 long 類型參數(shù)的構(gòu)造方法獲取的是距離 GMT 指定毫秒數(shù)的時(shí)間,60000 毫秒是一分鐘,而 GMT(格林尼治標(biāo)準(zhǔn)時(shí)間)與 CST(中央標(biāo)準(zhǔn)時(shí)間)相差 8 小時(shí),也就是說(shuō) 1970 年 1 月 1 日 00:00:00 GMT 與 1970 年 1 月 1 日 08:00:00 CST 表示的是同一時(shí)間。 因此距離 1970 年 1 月 1 日 00:00:00 CST 一分鐘的時(shí)間為 1970 年 1 月 1 日 00:01:00 CST,即使用 Date 對(duì)象表示為 Thu Jan 01 08:01:00 CST 1970。
常用方法
/** * <li>說(shuō)明: 日期時(shí)間工具類,針對(duì)日期的一些常用的處理方法。 * <li>創(chuàng)建日期:2022-05-04 * @author lyy */ public final class DateUtils { /** 日期格式“年月日”,yyyyMMdd(如20121231) */ public static final SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd"); /** 日期格式“年-月-日”,yyyy-MM-dd(如2012-12-31) */ public static final SimpleDateFormat yyyy_MM_dd = new SimpleDateFormat("yyyy-MM-dd"); /** 默認(rèn)日期格式“年-月-日” */ public static final SimpleDateFormat DEFAULT_FORMAT = yyyy_MM_dd; /** 日期格式“年-月-日 時(shí):分:秒”,yyyy-MM-dd HH:mm:ss(如2012-12-31 20:31:18) */ public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** 日期格式“年-月-日 時(shí):分:秒:毫秒”,yyyy-MM-dd HH:mm:ss(如2012-12-31 20:31:18) */ public static final SimpleDateFormat yyyy_MM_dd_HH_mm_ss_SSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); /** 日期格式“年-月-日 時(shí):分”,yyyy-MM-dd HH:mm(如2012-12-31 20:31) */ public static final SimpleDateFormat yyyy_MM_dd_HH_mm = new SimpleDateFormat("yyyy-MM-dd HH:mm"); /** 日期格式“年月日時(shí)分秒”,yyyyMMddHHmmss(如20121231203118) */ public static final SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss"); /** 日期格式“年月日時(shí)分秒毫秒”,yyyyMMddHHmmssSSS(如20121231203118978) */ public static final SimpleDateFormat yyyyMMddHHmmssSSS = new SimpleDateFormat("yyyyMMddHHmmssSSS"); /** 日期格式“年月日時(shí)分秒毫秒”,yyyy-MM-ddHH:mm:ssSSS(如2012-12-3120:31:18523) */ public static final SimpleDateFormat yyyy_MM_ddHH_mm_ssSSS = new SimpleDateFormat("yyyy-MM-ddHH:mm:ssSSS"); /** 日期格式“月日”,MMdd(如0121) */ public static final SimpleDateFormat MMdd = new SimpleDateFormat("MMdd"); /** * <li>說(shuō)明:禁止實(shí)例化該類 */ private DateUtils() {} /** * <li>說(shuō)明:使用默認(rèn)日期格式(yyyy-MM-dd)解析日期字符串 * @param String date:日期字符串 * @return Date 解析成功返回的日期對(duì)象 * @throws ParseException */ public static Date parse(String date) throws ParseException{ return DEFAULT_FORMAT.parse(date); } /** * <li>說(shuō)明:使用指定日期格式解析日期字符串 * @param String date:日期字符串 * @param String format:日期格式 * @return Date 解析成功返回的日期對(duì)象 * @throws ParseException */ public static Date parse(String date, String format) throws ParseException{ return new SimpleDateFormat(format).parse(date); } /** * <li>說(shuō)明:根據(jù)格式化字符串,返回當(dāng)前系統(tǒng)時(shí)間的字符串 * @param String format:日期時(shí)間格式化字符串 * @return String 當(dāng)前系統(tǒng)時(shí)間的字符串 * @throws */ public static String getToday(String format) { return new SimpleDateFormat(format).format(new Date()); } /** * 根據(jù)格式化字符串,返回指定時(shí)間的字符串 * @param date 指定時(shí)間 * @param format 日期時(shí)間格式化SimpleDateFormat * @return 指定時(shí)間的字符串 */ public static String format(Date date, SimpleDateFormat format) { if (date == null) { return null; } return format.format(date); } /** * <li>說(shuō)明:根據(jù)格式化對(duì)象,返回當(dāng)前系統(tǒng)時(shí)間的字符串 * @param format 日期時(shí)間格式化對(duì)象 * @return String 當(dāng)前系統(tǒng)時(shí)間的字符串 */ public static String getToday(SimpleDateFormat format) { return format.format(new Date()); } /** * <li>說(shuō)明:默認(rèn)返回當(dāng)前系統(tǒng)時(shí)間字符串,格式為“yyyy-MM-dd”。 * @return String 當(dāng)前系統(tǒng)時(shí)間字符串,格式為“yyyy-MM-dd * @throws */ public static String getToday() { return new SimpleDateFormat("yyyy-MM-dd").format(new Date()); } /** * <li>說(shuō)明:默認(rèn)返回當(dāng)前系統(tǒng)時(shí)間字符串,格式為“MMdd”。 * @return String 當(dāng)前系統(tǒng)時(shí)間字符串,格式為“yyyy-MM-dd * @throws */ public static String getTodayMMdd() { return MMdd.format(new Date()); } /** * <li>說(shuō)明:獲得兩個(gè)日期的月差 * @param Calendar one:第一個(gè)日歷對(duì)象 * @param Calendar two:第二個(gè)日歷對(duì)象 * @return int 相差的月數(shù) * @throws */ public static int monthDifference(Calendar one, Calendar two) { if (null == one || null == two) { throw new NullPointerException("參數(shù)對(duì)象為空。"); } Calendar after = one; Calendar before = two; if (one.before(two)) { after = two; before = one; } int deffYear = Math.abs(after.get(Calendar.YEAR) - before.get(Calendar.YEAR)); int deffMonth = after.get(Calendar.MONTH) - before.get(Calendar.MONTH); /*if (deffMonth < 0) { deffYear = deffYear - 1; deffMonth = Math.abs(deffMonth); }*/ //錯(cuò)誤的邏輯塊 return deffYear * 12 + deffMonth; } /** * <li>說(shuō)明:獲得兩個(gè)日期的月差 * @param Date one:第一個(gè)日期 * @param Date two:第二個(gè)日期 * @return int 相差的月數(shù) * @throws */ public static int monthDifference(Date one, Date two) { Calendar first = new GregorianCalendar(); first.setTime(one); Calendar second = new GregorianCalendar(); second.setTime(two); return monthDifference(first, second); } /** * <li>說(shuō)明:獲得兩個(gè)日期的月差 * @param String one:第一個(gè)日期字符串,格式必須為“yyyy-MM-dd” * @param String two:第二個(gè)日期字符串,格式必須為“yyyy-MM-dd” * @return int 相差的月數(shù) * @throws ParseException */ public static int monthDifference(String one, String two) throws ParseException { Format format = new SimpleDateFormat("yyyy-MM-dd"); Date first = (java.util.Date) format.parseObject(one); Date second = (java.util.Date) format.parseObject(two); return monthDifference(first, second); } /** * <li>說(shuō)明:是否為月的最后一天 * @param Calendar calendar:日歷對(duì)象 * @return boolean true=是,false=否 * @throws */ public static boolean isLastDayOfMonth(Calendar calendar) { Calendar today = calendar; Calendar tomorrow = (Calendar) calendar.clone(); tomorrow.add(Calendar.DAY_OF_MONTH, 1); int todayYear = today.get(Calendar.YEAR); int todayMonth = today.get(Calendar.MONTH) + 1; int tomorrowYear = tomorrow.get(Calendar.YEAR); int tomorrowMonth = tomorrow.get(Calendar.MONTH) + 1; //是否為當(dāng)月最后一天 if (tomorrowYear > todayYear || (tomorrowYear == todayYear && tomorrowMonth > todayMonth)) { return true; } return false; } /** * <li>說(shuō)明: 是否為月的最后一天 * @param Date date:日期對(duì)象 * @return boolean true=是,false=否 * @throws */ public static boolean isLastDayOfMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return isLastDayOfMonth(calendar); } /** * <li>說(shuō)明:當(dāng)前系統(tǒng)時(shí)間當(dāng)天是否為月的最后一天 * @return boolean true=是,false=否 * @throws */ public static boolean isLastDayOfMonth() { return isLastDayOfMonth(Calendar.getInstance()); } /** * <li>說(shuō)明:將數(shù)字表示的月份轉(zhuǎn)換位成中文表示的月份 * @param int month:數(shù)字月份 * @return String 中文月份 * @throws */ public static String convertMonth(int month) { switch (month) { case Calendar.JANUARY: return "一月"; case Calendar.FEBRUARY: return "二月"; case Calendar.MARCH: return "三月"; case Calendar.APRIL: return "四月"; case Calendar.MAY: return "五月"; case Calendar.JUNE: return "六月"; case Calendar.JULY: return "七月"; case Calendar.AUGUST: return "八月"; case Calendar.SEPTEMBER: return "九月"; case Calendar.OCTOBER: return "十月"; case Calendar.NOVEMBER: return "十一月"; case Calendar.DECEMBER: return "十二月"; default: throw new IllegalArgumentException("表示月份的參數(shù)無(wú)效:" + month); } } /** * <li>說(shuō)明:將數(shù)字表示的周天轉(zhuǎn)換位成中文表示的周天 * @param int dayOfWeek:該天在一周內(nèi)的數(shù)字序號(hào),從0開(kāi)始(周日0-周六6) * @return String 返回具體周天名稱 * @throws */ public static String convertDayOfWeek(int dayOfWeek) { switch (dayOfWeek) { case Calendar.SUNDAY: return "周日"; case Calendar.MONDAY: return "周一"; case Calendar.TUESDAY: return "周二"; case Calendar.WEDNESDAY: return "周三"; case Calendar.THURSDAY: return "周四"; case Calendar.FRIDAY: return "周五"; case Calendar.SATURDAY: return "周六"; default: throw new IllegalArgumentException("參數(shù)無(wú)效:" + dayOfWeek); } } /** * <li>說(shuō)明:將數(shù)字表示的周天轉(zhuǎn)換位成中文表示的星期 * @param int dayOfWeek:該天在一星期內(nèi)的數(shù)字序號(hào),從0開(kāi)始(星期天0-星期六6) * @return String 星期幾名稱 * @throws */ public static String convertDayOfWeek2(int dayOfWeek) { switch (dayOfWeek) { case Calendar.SUNDAY: return "星期天"; case Calendar.MONDAY: return "星期一"; case Calendar.TUESDAY: return "星期二"; case Calendar.WEDNESDAY: return "星期三"; case Calendar.THURSDAY: return "星期四"; case Calendar.FRIDAY: return "星期五"; case Calendar.SATURDAY: return "星期六"; default: throw new IllegalArgumentException("參數(shù)無(wú)效:" + dayOfWeek); } } /** * <li>說(shuō)明:獲取當(dāng)天是星期幾。 * 注意:不能使用new Date().getDay()獲取當(dāng)天在星期中的位置,應(yīng)該使用Calendar.getInstance().get(Calendar.DAY_OF_WEEK)獲取當(dāng)天在星期中的位置 * @return String 星期幾名稱 * @throws */ public static String getTodayOfWeek2() { return convertDayOfWeek2(Calendar.getInstance().get(Calendar.DAY_OF_WEEK)); } /** * <li>說(shuō)明:獲取當(dāng)天是周幾。 * 注意:不能使用new Date().getDay()獲取當(dāng)天在星期中的位置,應(yīng)該使用Calendar.getInstance().get(Calendar.DAY_OF_WEEK)獲取當(dāng)天在星期中的位置 * @return String 返回具體周天名稱 * @throws */ public static String getTodayOfWeek() { return convertDayOfWeek(Calendar.getInstance().get(Calendar.DAY_OF_WEEK)); } /** * * <li>說(shuō)明:將毫秒數(shù)轉(zhuǎn)換為日期格式的字符串 * @param millSeconds 毫秒數(shù) * @param parseStr 日期格式化字符串 如"yyyy-MM-dd hh:mm:ss" * @return 日期格式的字符串 */ public static String getDateByMillSeconds(long millSeconds, String parseStr){ java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(parseStr); String sb=format.format(getDateByMillSeconds(millSeconds)); return sb; } /** * * <li>說(shuō)明:將毫秒數(shù)轉(zhuǎn)換為日期 * @param millSeconds 毫秒數(shù) * @return 日期 */ public static Date getDateByMillSeconds(long millSeconds){ Date date = new Date(millSeconds); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); return gc.getTime(); } /** * * <li>說(shuō)明:獲取服務(wù)器時(shí)間,本月的第一天 * @return 獲取服務(wù)器時(shí)間,本月的第一天 */ public static String getFirstDayByCurrentMonth(){ Calendar calendar = new GregorianCalendar(); calendar.set( Calendar.DATE, 1 ); SimpleDateFormat simpleFormate = new SimpleDateFormat( "yyyy-MM-dd" ); return simpleFormate.format(calendar.getTime()); } /** * * <li>說(shuō)明:獲取服務(wù)器時(shí)間, 本月的最后一天 * @return 獲取服務(wù)器時(shí)間, 本月的最后一天 */ public static String getLastDayByCurrentMonth(){ Calendar calendar = new GregorianCalendar(); calendar.set( Calendar.DATE, 1 ); calendar.roll(Calendar.DATE, - 1 ); SimpleDateFormat simpleFormate = new SimpleDateFormat( "yyyy-MM-dd" ); return simpleFormate.format(calendar.getTime()); } /** * * <li>說(shuō)明:獲取實(shí)際工期(分鐘數(shù))臨時(shí)使用,以后有工作日歷再做修改 * @param realStartDate 實(shí)際開(kāi)工時(shí)間 * @param realEndDate 實(shí)際完工時(shí)間 * @return 實(shí)際工期(分鐘數(shù)) * @throws Exception */ public static Long getRealWorkminutes(Date realStartDate, Date realEndDate) throws Exception{ BigDecimal realWorkminutes = new BigDecimal("0"); long startTime = 0l; long endTime = 0l; long timeInterval = 0l; if(realStartDate != null && realEndDate != null) { startTime = realStartDate.getTime(); endTime = realEndDate.getTime(); timeInterval = endTime - startTime; if(timeInterval > 0){ int day = (int)timeInterval/(24*60*60*1000); int hour = (int)timeInterval/(60*60*1000)-day*24; int min = (int)(timeInterval/(60*1000))-day*24*60-hour*60; if(day >= 1){ realWorkminutes = new BigDecimal(day*8*60); if(hour >= 1){ realWorkminutes = realWorkminutes.add(new BigDecimal(hour*20)); } if(min >=1){ realWorkminutes = realWorkminutes.add(new BigDecimal(min)); } }else{ if(hour >= 1){ realWorkminutes = realWorkminutes.add(new BigDecimal(hour*60>=480?480:hour*60)); } if(min >=1){ realWorkminutes = realWorkminutes.add(new BigDecimal(min)); } if(realWorkminutes.compareTo(new BigDecimal(480)) > 0) realWorkminutes = new BigDecimal(480); } } } return Long.valueOf(String.valueOf(realWorkminutes)); } /** * <li>說(shuō)明:得到兩個(gè)日期間隔的天數(shù) * @param String beginDate 開(kāi)始日期"yyyy-MM-dd" * @param String endDate 結(jié)束日期"yyyy-MM-dd" * @return int 相差天數(shù) * @throws ParseException */ public static int getDaysBetween(String beginDate, String endDate) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date bDate = format.parse(beginDate); Date eDate = format.parse(endDate); return getDaysBetween(bDate, eDate); } /** * <li>說(shuō)明:得到兩個(gè)日期間隔的天數(shù) * @param Date beginDate 開(kāi)始日期 * @param Date endDate 結(jié)束日期 * @return int 相差天數(shù) * @throws ParseException */ public static int getDaysBetween(Date beginDate, Date endDate) throws ParseException { Calendar g1 = new GregorianCalendar(); g1.setTime(beginDate); Calendar g2 = new GregorianCalendar(); g2.setTime(endDate); int elapsed = 0; GregorianCalendar gc1, gc2; if (g2.after(g1)) { gc2 = (GregorianCalendar) g2.clone(); gc1 = (GregorianCalendar) g1.clone(); } else { gc2 = (GregorianCalendar) g1.clone(); gc1 = (GregorianCalendar) g2.clone(); } gc1.clear(Calendar.MILLISECOND); gc1.clear(Calendar.SECOND); gc1.clear(Calendar.MINUTE); gc1.clear(Calendar.HOUR_OF_DAY); gc2.clear(Calendar.MILLISECOND); gc2.clear(Calendar.SECOND); gc2.clear(Calendar.MINUTE); gc2.clear(Calendar.HOUR_OF_DAY); while (gc1.before(gc2)) { gc1.add(Calendar.DATE, 1); elapsed++; } return elapsed; } /** * <li>說(shuō)明:根據(jù)開(kāi)始時(shí)間和時(shí)長(zhǎng)獲取完成時(shí)間 * @param startTime 開(kāi)始時(shí)間 * @param timeInterval 時(shí)長(zhǎng) * @return 完成時(shí)間 */ public static long getFinalTime(long startTime, long timeInterval) { return startTime + timeInterval; } }
到此這篇關(guān)于Java時(shí)間工具類Date的常用處理方法的文章就介紹到這了,更多相關(guān)Java時(shí)間工具類Date內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java8深入學(xué)習(xí)系列(二)函數(shù)式編程
函數(shù)式編程,這個(gè)詞語(yǔ)由兩個(gè)名詞構(gòu)成,函數(shù),編程。編程這個(gè)詞我就不用解釋了,大家都是做這個(gè)的。函數(shù),其實(shí)單獨(dú)抽離出來(lái)這個(gè)詞語(yǔ),也并不陌生,那二者組合后的到底是什么呢,下面這篇文章主要給大家介紹了關(guān)于Java8函數(shù)式編程的相關(guān)資料,需要的朋友可以參考下。2017-08-08Spring?Boot請(qǐng)求處理之常用參數(shù)注解使用教程
這篇文章主要給大家介紹了關(guān)于Spring?Boot請(qǐng)求處理之常用參數(shù)注解使用的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-03-03SpringBoot?2.5.5整合輕量級(jí)的分布式日志標(biāo)記追蹤神器TLog的詳細(xì)過(guò)程
分布式追蹤系統(tǒng)是一個(gè)最終的解決方案,如果您的公司已經(jīng)上了分布式追蹤系統(tǒng),這篇文章主要介紹了SpringBoot?2.5.5整合輕量級(jí)的分布式日志標(biāo)記追蹤神器TLog,需要的朋友可以參考下2022-10-10Java使用阻塞隊(duì)列控制線程通信的方法實(shí)例詳解
這篇文章主要介紹了Java使用阻塞隊(duì)列控制線程通信的方法,結(jié)合實(shí)例形式詳細(xì)分析了java使用阻塞隊(duì)列控制線程通信的相關(guān)原理、方法及操作注意事項(xiàng),需要的朋友可以參考下2019-09-09SpringBoot2.0整合jackson配置日期格式化和反序列化的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot2.0整合jackson配置日期格式化和反序列化的實(shí)現(xiàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-11-11JAVA編程實(shí)現(xiàn)TCP網(wǎng)絡(luò)通訊的方法示例
這篇文章主要介紹了JAVA編程實(shí)現(xiàn)TCP網(wǎng)絡(luò)通訊的方法,簡(jiǎn)單說(shuō)明了TCP通訊的原理并結(jié)合具體實(shí)例形式分析了java實(shí)現(xiàn)TCP通訊的步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-08-08Java后端學(xué)習(xí)精華之TCP通信傳輸協(xié)議詳解
TCP/IP是一種面向連接的、可靠的、基于字節(jié)流的傳輸層通信協(xié)議,它會(huì)保證數(shù)據(jù)不丟包、不亂序。TCP全名是Transmission Control Protocol,它是位于網(wǎng)絡(luò)OSI模型中的第四層2021-09-09PipedWriter和PipedReader源碼分析_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了PipedWriter和PipedReader源碼分析_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理,需要的朋友可以參考下2017-05-05Java使用poi組件導(dǎo)出Excel格式數(shù)據(jù)
這篇文章主要介紹了Java使用poi組件導(dǎo)出Excel格式數(shù)據(jù),需要的朋友可以參考下2020-02-02