您好,登錄后才能下訂單哦!
本文小編為大家詳細介紹“Java日期工具類的編寫方法有哪些”,內容詳細,步驟清晰,細節處理妥當,希望這篇“Java日期工具類的編寫方法有哪些”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
將字符串轉換為對應日期
Date date = simpleDateFormat.parse(string);
將日期轉換為字符串
String string = simpleDateFormat.format(date);
注意,因為可能定義的格式和實際字符串提供的格式不符合,所以會拋出異常。
將年月日的漢字日期轉為 - - 分隔符的日期
public static void main(String[] args) throws ParseException { //統一日期格式 String StrVal = "2018年05月22日"; Date d1 = new SimpleDateFormat("yyyy年MM月dd日").parse(StrVal); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String time = format.format(d1); System.out.println(time); }
/** * 將日期對象格式化為指定格式的日期字符串 * @param date 傳入的日期對象 * @param format 格式 * @return */ public static String formatDate(Date date,String format){ String result=""; SimpleDateFormat sdf=new SimpleDateFormat(format); if(date!=null){ result=sdf.format(date); } return result; } /** * 將日期字符串轉換成一個日期對象 * @param dateStr 日期字符串 * @param format 格式 * @return * @throws ParseException */ public static Date formatDate(String dateStr,String format) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat(format); return sdf.parse(dateStr); } public static void main(String[] args) throws ParseException { Date date=new Date(); System.out.println(formatDate(date,"yyyy-MM-dd")); System.out.println(formatDate(date,"yyyy-MM-dd HH:mm:ss")); System.out.println(formatDate(date,"yyyy年MM月dd日HH時mm分ss秒")); String dataStr="1989-11-02 18:01:41"; Date date2=formatDate(dataStr,"yyyy-MM-dd HH:mm:ss"); System.out.println(formatDate(date2,"yyyy-MM-dd HH:mm:ss")); }
運行輸出:
2016-11-02
2016-11-02 18:06:50
2016年11月02日18時06分50秒
1989-11-02 18:01:41
SimpleDateFormat類主要是用作日期類型轉換用的,常用的日期格式化
public static void main(String[] args) { //默認輸出格式 Date date=new Date(); System.out.println(date); //日期格式化顯示,首先定義格式 SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf4=new SimpleDateFormat("yyyy年MM月dd日HH時mm分ss秒"); //將格式應用于日期 System.out.println(sdf1.format(date)); System.out.println(sdf2.format(date)); System.out.println(sdf3.format(date)); System.out.println(sdf4.format(date)); }
Calendar有個DAY_OF_WEEK 可以返回一個星期中的第幾天;
這里說下注意點 老外的第一天是從星期日開始的,所以要-1;
import java.util.Calendar; public class Test { public static void main(String[] args) { String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; Calendar calendar=Calendar.getInstance(); System.out.println("今天是"+weekDays[calendar.get(Calendar.DAY_OF_WEEK)-1]); } }
對日歷進行操作
public static void main(String[] args) { //默認輸出格式 Date now = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String time = format.format(now); System.out.println(time); Calendar calendar = Calendar.getInstance(); calendar.setTime(now); calendar.add(Calendar.MONTH, 1); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String nowTime = sdf.format(calendar.getTime()); System.out.println(nowTime); calendar.add(Calendar.MONTH, -2); String nowTime2 = sdf.format(calendar.getTime()); System.out.println(nowTime2); }
獲取時間
賦值時年月日時分秒常用的6個值,注意月份下標從0開始,所以取月份要+1
public static void main(String[] args) { //默認輸出格式 Date now = new Date(); SimpleDateFormat nowSdf = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(nowSdf.format(now)); Calendar calendar = Calendar.getInstance(); // 賦值時年月日時分秒常用的6個值,注意月份下標從0開始,所以取月份要+1 System.out.println("年:" + calendar.get(Calendar.YEAR)); System.out.println("月:" + (calendar.get(Calendar.MONTH) + 1)); System.out.println("日:" + calendar.get(Calendar.DAY_OF_MONTH)); System.out.println("時:" + calendar.get(Calendar.HOUR_OF_DAY)); System.out.println("分:" + calendar.get(Calendar.MINUTE)); System.out.println("秒:" + calendar.get(Calendar.SECOND)); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String nowTime2 = sdf.format(calendar.getTime()); System.out.println(nowTime2); }
設置時間
如果想設置為某個日期,可以一次設置年月日時分秒,由于月份下標從0開始賦值月份要-1
public static void main(String[] args) { //默認輸出格式 Date now = new Date(); SimpleDateFormat nowSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(nowSdf.format(now)); Calendar calendar = Calendar.getInstance(); calendar.set(2013, 5, 4, 13, 44, 51); calendar.set(Calendar.YEAR, 2014);//年 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime = sdf.format(calendar.getTime()); System.out.println(nowTime); calendar.set(Calendar.MONTH, 7);//月(月份0代表1月) SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime1 = sdf1.format(calendar.getTime()); System.out.println(nowTime1); calendar.set(Calendar.DATE, 11);//日 calendar.set(Calendar.HOUR_OF_DAY, 15);//時 calendar.set(Calendar.MINUTE, 33);//分 calendar.set(Calendar.SECOND, 32);//秒 }
時間計算
public static void main(String[] args) { //默認輸出格式 Date now = new Date(); SimpleDateFormat nowSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(nowSdf.format(now)); Calendar calendar = Calendar.getInstance(); calendar.setTime(now); calendar.add(Calendar.YEAR, 1);//年 calendar.add(Calendar.MONTH, 1);//月 calendar.add(Calendar.DATE, 1);//日 //calendar.add(Calendar.DAY_OF_YEAR, 1);//今年的第 N 天 //calendar.add(Calendar.DAY_OF_MONTH, 1); // 本月第 N 天 //calendar.add(Calendar.DAY_OF_WEEK, 1);// 本周幾 calendar.add(Calendar.HOUR_OF_DAY, -1);//時 calendar.add(Calendar.MINUTE, 1);//分 calendar.add(Calendar.SECOND, 1);//秒 //calendar.add(calendar.WEEK_OF_MONTH, 1);//增加一個禮拜 //calendar.add(calendar.WEEK_OF_YEAR,1);//增加一個禮拜 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime1 = sdf1.format(calendar.getTime()); System.out.println(nowTime1); }
日期的計算
獲取本月最小天數與最大天數
public static void main(String[] args) { //默認輸出格式 Date now = new Date(); SimpleDateFormat nowSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); int firstD = calendar.getActualMinimum(calendar.DAY_OF_MONTH); int lastD = calendar.getActualMaximum(calendar.DAY_OF_MONTH); System.out.println("獲取本月的第一天和最后天:" + firstD +"," + lastD); }
獲取本周星期一、上周星期一、這周星期一
public static Date geLastWeekMonday(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(getThisWeekMonday(date)); cal.add(Calendar.DATE, -7); return cal.getTime(); } public static Date getThisWeekMonday(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); // 獲得當前日期是一個星期的第幾天 int dayWeek = cal.get(Calendar.DAY_OF_WEEK); if (1 == dayWeek) { cal.add(Calendar.DAY_OF_MONTH, -1); } // 設置一個星期的第一天,按中國的習慣一個星期的第一天是星期一 cal.setFirstDayOfWeek(Calendar.MONDAY); // 獲得當前日期是一個星期的第幾天 int day = cal.get(Calendar.DAY_OF_WEEK); // 根據日歷的規則,給當前日期減去星期幾與一個星期第一天的差值 cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day); return cal.getTime(); } public static Date getNextWeekMonday(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(getThisWeekMonday(date)); cal.add(Calendar.DATE, 7); return cal.getTime(); } public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = sdf.parse("2017-09-10"); System.out.println("今天是" + sdf.format(date)); System.out.println("上周一" + sdf.format(geLastWeekMonday(date))); System.out.println("本周一" + sdf.format(getThisWeekMonday(date))); System.out.println("下周一" + sdf.format(getNextWeekMonday(date))); } catch (Exception e) { e.printStackTrace(); } }
天數計算
用Date類計算日期差
public static void main(String[] args) { Calendar love = Calendar.getInstance(); Calendar now = Calendar.getInstance(); love.set(2016, 8, 6); //真實的日期是2016-9-6; int days = (int) ((now.getTimeInMillis() - love.getTimeInMillis()) / (24 * 60 * 60 * 1000.0)); System.out.println(days); }
public static void main(String[] args) throws ParseException { SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");//大小寫還是很重要的 Date LoveDay=new Date(); Date now=new Date(); LoveDay=format.parse("2016-08-06"); int day=(int) ((now.getTime()-LoveDay.getTime())/(24*60*60*1000)); System.out.println(day); }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtils { public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; public static final String MINUTE_PATTERN = "yyyy-MM-dd HH:mm"; public static final String HOUR_PATTERN = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_PATTERN = "yyyy-MM-dd"; public static final String MONTH_PATTERN = "yyyy-MM"; public static final String YEAR_PATTERN = "yyyy"; public static final String MINUTE_ONLY_PATTERN = "mm"; public static final String HOUR_ONLY_PATTERN = "HH"; /** * 日期相加減天數 * @param date 如果為Null,則為當前時間 * @param days 加減天數 * @param includeTime 是否包括時分秒,true表示包含 * @return * @throws ParseException */ public static Date dateAdd(Date date, int days, boolean includeTime) throws ParseException{ if(date == null){ date = new Date(); } if(!includeTime){ SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_PATTERN); date = sdf.parse(sdf.format(date)); } Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); return cal.getTime(); } /** * 時間格式化成字符串 * @param date Date * @param pattern StrUtils.DATE_TIME_PATTERN || StrUtils.DATE_PATTERN, 如果為空,則為yyyy-MM-dd * @return * @throws ParseException */ public static String dateFormat(Date date, String pattern) throws ParseException{ if(pattern==null||pattern.length()==0||pattern.equals(" ")){ pattern = DateUtils.DATE_PATTERN; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.format(date); } /** * 字符串解析成時間對象 * @param dateTimeString String * @param pattern StrUtils.DATE_TIME_PATTERN || StrUtils.DATE_PATTERN,如果為空,則為yyyy-MM-dd * @return * @throws ParseException */ public static Date dateParse(String dateTimeString, String pattern) throws ParseException{ if(pattern==null||pattern.length()==0||pattern.equals(" ")){ pattern = DateUtils.DATE_PATTERN; } SimpleDateFormat sdf = new SimpleDateFormat(pattern); return sdf.parse(dateTimeString); } /** * 將日期時間格式成只有日期的字符串(可以直接使用dateFormat,Pattern為Null進行格式化) * @param dateTime Date * @return * @throws ParseException */ public static String dateTimeToDateString(Date dateTime) throws ParseException{ String dateTimeString = DateUtils.dateFormat(dateTime, DateUtils.DATE_TIME_PATTERN); return dateTimeString.substring(0, 10); } /** * 當時、分、秒為00:00:00時,將日期時間格式成只有日期的字符串, * 當時、分、秒不為00:00:00時,直接返回 * @param dateTime Date * @return * @throws ParseException */ public static String dateTimeToDateStringIfTimeEndZero(Date dateTime) throws ParseException{ String dateTimeString = DateUtils.dateFormat(dateTime, DateUtils.DATE_TIME_PATTERN); if(dateTimeString.endsWith("00:00:00")){ return dateTimeString.substring(0, 10); }else{ return dateTimeString; } } /** * 將日期時間格式成日期對象,和dateParse互用 * @param dateTime Date * @return Date * @throws ParseException */ public static Date dateTimeToDate(Date dateTime) throws ParseException{ Calendar cal = Calendar.getInstance(); cal.setTime(dateTime); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } /** * 時間加減小時 * @param startDate 要處理的時間,Null則為當前時間 * @param hours 加減的小時 * @return Date */ public static Date dateAddHours(Date startDate, int hours) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.HOUR, c.get(Calendar.HOUR) + hours); return c.getTime(); } /** * 時間加減分鐘 * @param startDate 要處理的時間,Null則為當前時間 * @param minutes 加減的分鐘 * @return */ public static Date dateAddMinutes(Date startDate, int minutes) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + minutes); return c.getTime(); } /** * 時間加減秒數 * @param startDate 要處理的時間,Null則為當前時間 * @param minutes 加減的秒數 * @return */ public static Date dateAddSeconds(Date startDate, int seconds) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.SECOND, c.get(Calendar.SECOND) + seconds); return c.getTime(); } /** * 時間加減天數 * @param startDate 要處理的時間,Null則為當前時間 * @param days 加減的天數 * @return Date */ public static Date dateAddDays(Date startDate, int days) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.DATE, c.get(Calendar.DATE) + days); return c.getTime(); } /** * 時間加減月數 * @param startDate 要處理的時間,Null則為當前時間 * @param months 加減的月數 * @return Date */ public static Date dateAddMonths(Date startDate, int months) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.MONTH, c.get(Calendar.MONTH) + months); return c.getTime(); } /** * 時間加減年數 * @param startDate 要處理的時間,Null則為當前時間 * @param years 加減的年數 * @return Date */ public static Date dateAddYears(Date startDate, int years) { if (startDate == null) { startDate = new Date(); } Calendar c = Calendar.getInstance(); c.setTime(startDate); c.set(Calendar.YEAR, c.get(Calendar.YEAR) + years); return c.getTime(); } /** * 時間比較(如果myDate>compareDate返回1,<返回-1,相等返回0) * @param myDate 時間 * @param compareDate 要比較的時間 * @return int */ public static int dateCompare(Date myDate, Date compareDate) { Calendar myCal = Calendar.getInstance(); Calendar compareCal = Calendar.getInstance(); myCal.setTime(myDate); compareCal.setTime(compareDate); return myCal.compareTo(compareCal); } /** * 獲取兩個時間中最小的一個時間 * @param date * @param compareDate * @return */ public static Date dateMin(Date date, Date compareDate) { if(date == null){ return compareDate; } if(compareDate == null){ return date; } if(1 == dateCompare(date, compareDate)){ return compareDate; }else if(-1 == dateCompare(date, compareDate)){ return date; } return date; } /** * 獲取兩個時間中最大的一個時間 * @param date * @param compareDate * @return */ public static Date dateMax(Date date, Date compareDate) { if(date == null){ return compareDate; } if(compareDate == null){ return date; } if(1 == dateCompare(date, compareDate)){ return date; }else if(-1 == dateCompare(date, compareDate)){ return compareDate; } return date; } /** * 獲取兩個日期(不含時分秒)相差的天數,不包含今天 * @param startDate * @param endDate * @return * @throws ParseException */ public static int dateBetween(Date startDate, Date endDate) throws ParseException { Date dateStart = dateParse(dateFormat(startDate, DATE_PATTERN), DATE_PATTERN); Date dateEnd = dateParse(dateFormat(endDate, DATE_PATTERN), DATE_PATTERN); return (int) ((dateEnd.getTime() - dateStart.getTime())/1000/60/60/24); } /** * 獲取兩個日期(不含時分秒)相差的天數,包含今天 * @param startDate * @param endDate * @return * @throws ParseException */ public static int dateBetweenIncludeToday(Date startDate, Date endDate) throws ParseException { return dateBetween(startDate, endDate) + 1; } /** * 獲取日期時間的年份,如2017-02-13,返回2017 * @param date * @return */ public static int getYear(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.YEAR); } /** * 獲取日期時間的月份,如2017年2月13日,返回2 * @param date * @return */ public static int getMonth(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.MONTH) + 1; } /** * 獲取日期時間的第幾天(即返回日期的dd),如2017-02-13,返回13 * @param date * @return */ public static int getDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.get(Calendar.DATE); } /** * 獲取日期時間當月的總天數,如2017-02-13,返回28 * @param date * @return */ public static int getDaysOfMonth(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.getActualMaximum(Calendar.DATE); } /** * 獲取日期時間當年的總天數,如2017-02-13,返回2017年的總天數 * @param date * @return */ public static int getDaysOfYear(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal.getActualMaximum(Calendar.DAY_OF_YEAR); } /** * 根據時間獲取當月最大的日期 * <li>2017-02-13,返回2017-02-28</li> * <li>2016-02-13,返回2016-02-29</li> * <li>2016-01-11,返回2016-01-31</li> * @param date Date * @return * @throws Exception */ public static Date maxDateOfMonth(Date date) throws Exception { Calendar cal = Calendar.getInstance(); cal.setTime(date); int value = cal.getActualMaximum(Calendar.DATE); return dateParse(dateFormat(date, MONTH_PATTERN) + "-" + value, null); } /** * 根據時間獲取當月最小的日期,也就是返回當月的1號日期對象 * @param date Date * @return * @throws Exception */ public static Date minDateOfMonth(Date date) throws Exception { Calendar cal = Calendar.getInstance(); cal.setTime(date); int value = cal.getActualMinimum(Calendar.DATE); return dateParse(dateFormat(date, MONTH_PATTERN) + "-" + value, null); } }
public static void main(String[] args) throws Exception { System.out.println(dateTimeToDate(new Date())); System.out.println(dateParse("2017-02-04 14:58:20", null)); System.out.println(dateTimeToDateStringIfTimeEndZero(new Date())); System.out.println(dateTimeToDateStringIfTimeEndZero(dateTimeToDate(new Date()))); System.out.println(dateBetween(dateParse("2017-01-30", null), dateParse("2017-02-01", null))); System.out.println(dateBetweenIncludeToday(dateParse("2017-01-30", null), dateParse("2017-02-01", null))); System.out.println(getDate(dateParse("2017-01-17", null))); System.out.println(getDaysOfMonth(dateParse("2017-02-01", null))); System.out.println(getDaysOfYear(dateParse("2017-01-30", null))); /* System.out.println(dateFormat(dateAddMonths(dateParse("2017-02-07", StrUtils.MONTH_PATTERN), -12), StrUtils.MONTH_PATTERN));*/ System.out.println(dateFormat(maxDateOfMonth(dateParse("2016-02", "yyyy-MM")), null)); System.out.println(dateFormat(minDateOfMonth(dateParse("2016-03-31", null)), null)); }
讀到這里,這篇“Java日期工具類的編寫方法有哪些”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。