java date 工具類 DateUtil 格式轉換
package systems.baseutil.tool; /** * <p>Title: 時間和日期的工具類</p> * <p>Description: DateUtil類包含了標準的時間和日期格式,以及這些格式在字串及日期之間轉換的方法</p> * <p>Copyright: Copyright (c) 2007 advance,Inc. All Rights Reserved</p> * <p>Company: advance,Inc.</p> * @author advance * @version 1.0 */ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateUtil { //~ Static fields/initializers ============================================= private static String datePattern = "MM/dd/yyyy"; private static String datePattern2 = "yyyy-MM-dd HH:mm:ss"; private static String datePattern3= "yyyy-MM-dd"; private static String datePattern4= "yyyy-MM"; private static String timePattern = datePattern + " HH:MM a"; //~ Methods ================================================================ /** * Return default datePattern (MM/dd/yyyy) * @return a string representing the date pattern on the UI */ public static String getDatePattern() { return datePattern; } /** * This method attempts to convert an Oracle-formatted date * in the form dd-MMM-yyyy to mm/dd/yyyy. * * @param aDate date from database as a string * @return formatted string for the ui */ public static final String getDate(Date aDate) { SimpleDateFormat df = null; String returnValue = ""; if (aDate != null) { df = new SimpleDateFormat(datePattern); returnValue = df.format(aDate); } return (returnValue); } public static final String date2Str(Date aDate) { SimpleDateFormat df = null; String returnValue = ""; if (aDate != null) { df = new SimpleDateFormat(datePattern); returnValue = df.format(aDate); } return (returnValue); } public static final String date2Str(String pattern, Date aDate) { SimpleDateFormat df = null; String returnValue = ""; if (aDate != null) { df = new SimpleDateFormat(pattern); returnValue = df.format(aDate); } return (returnValue); } /** * This method generates a string representation of a date/time * in the format you specify on input * * @param aMask the date pattern the string is in * @param strDate a string representation of a date * @return a converted Date object * @see java.text.SimpleDateFormat * @throws ParseException */ public static final Date convertStringToDate(String aMask, String strDate) throws ParseException { SimpleDateFormat df = null; Date date = null; df = new SimpleDateFormat(aMask); try { date = df.parse(strDate); } catch (ParseException pe) { return null; } return (date); } public static final Date str2Date(String aMask, String strDate) throws ParseException { SimpleDateFormat df = null; Date date = null; df = new SimpleDateFormat(aMask); try { date = df.parse(strDate); } catch (ParseException pe) { return null; } return (date); } /** * This method returns the current date time in the format: * MM/dd/yyyy HH:MM a * * @param theTime the current time * @return the current date/time */ public static String getTimeNow(Date theTime) { return getDateTime(timePattern, theTime); } /** * This method returns the current date in the format: MM/dd/yyyy * * @return the current date * @throws ParseException */ public static Calendar getToday() throws ParseException { Date today = new Date(); SimpleDateFormat df = new SimpleDateFormat(datePattern); // This seems like quite a hack (date -> string -> date), // but it works ;-) String todayAsString = df.format(today); Calendar cal = new GregorianCalendar(); cal.setTime(convertStringToDate(todayAsString)); return cal; } /** * This method generates a string representation of a date's date/time * in the format you specify on input * * @param aMask the date pattern the string is in * @param aDate a date object * @return a formatted string representation of the date * * @see java.text.SimpleDateFormat */ public static final String getDateTime(String aMask, Date aDate) { SimpleDateFormat df = null; String returnValue = ""; if (aDate == null) { System.out.print("aDate is null!"); } else { df = new SimpleDateFormat(aMask); returnValue = df.format(aDate); } return (returnValue); } /** * This method generates a string representation of a date based * on the System Property 'dateFormat' * in the format you specify on input * * @param aDate A date to convert * @return a string representation of the date */ public static final String convertDateToString(Date aDate) { return getDateTime(datePattern, aDate); } /** * This method converts a String to a date using the datePattern * * @param strDate the date to convert (in format MM/dd/yyyy) * @return a date object * * @throws ParseException */ public static Date convertStringToDate(String strDate) throws ParseException { Date aDate = null; try { aDate = convertStringToDate(datePattern, strDate); } catch (ParseException pe) { //log.error("Could not convert '" + strDate // + "' to a date, throwing exception"); pe.printStackTrace(); return null; } return aDate; } //日期格式轉換成時間戳 public static long getTimeStamp(String pattern, String strDate) { long returnTimeStamp = 0; Date aDate = null; try { aDate = convertStringToDate(pattern, strDate); } catch (ParseException pe) { aDate = null; } if (aDate == null) { returnTimeStamp = 0; } else { returnTimeStamp = aDate.getTime(); } return returnTimeStamp; } //獲取當前日期的郵戳 public static long getNowTimeStamp() { long returnTimeStamp = 0; Date aDate = null; try { aDate = convertStringToDate("yyyy-MM-dd HH:mm:ss", getNowDateTime()); } catch (ParseException pe) { aDate = null; } if (aDate == null) { returnTimeStamp = 0; } else { returnTimeStamp = aDate.getTime(); } return returnTimeStamp; } /** *得到格式化後的系統當前日期 *@param strScheme 格式模式字串 *@return 格式化後的系統當前時間,如果有異常產生,返回空串"" *@see java.util.SimpleDateFormat */ public static final String getNowDateTime(String strScheme) { String strReturn = null; Date now = new Date(); try { SimpleDateFormat sdf = new SimpleDateFormat(strScheme); strReturn = sdf.format(now); } catch (Exception e) { strReturn = ""; } return strReturn; } public static final String getNowDateTime() { String strReturn = null; Date now = new Date(); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); strReturn = sdf.format(now); } catch (Exception e) { strReturn = ""; } return strReturn; } /** *轉化日期格式"MM/dd/YY、MM.dd.YY、MM-dd-YY、MM/dd/YY",並輸出為正常的格式yyyy-MM-dd *@param strDate 待轉換的日期格式 *@return 格式化後的日期,如果有異常產生,返回空串"" *@see java.util.SimpleDateFormat */ public static final String convertNormalDate(String strDate) { String strReturn = null; //先把傳入引數分格符轉換成java認識的分格符 String[] date_arr = strDate.split("\\.|\\/|\\-"); try { if (date_arr.length == 3) { if (date_arr[2].length() != 4) { String nowYear = getNowDateTime("yyyy"); date_arr[2] = nowYear.substring(0, 2) + date_arr[2]; } strReturn = DateUtil.getDateTime("yyyy-MM-dd", convertStringToDate(combineStringArray(date_arr, "/"))); } } catch (Exception e) { return strReturn; } return strReturn; } /** * 將字串陣列使用指定的分隔符合併成一個字串。 * @param array 字串陣列 * @param delim 分隔符,為null的時候使用""作為分隔符(即沒有分隔符) * @return 合併後的字串 * @since 0.4 */ public static final String combineStringArray(String[] array, String delim) { int length = array.length - 1; if (delim == null) { delim = ""; } StringBuffer result = new StringBuffer(length * 8); for (int i = 0; i < length; i++) { result.append(array[i]); result.append(delim); } result.append(array[length]); return result.toString(); } public static final int getWeekNum(String strWeek) { int returnValue = 0; if (strWeek.equals("Mon")) { returnValue = 1; } else if (strWeek.equals("Tue")) { returnValue = 2; } else if (strWeek.equals("Wed")) { returnValue = 3; } else if (strWeek.equals("Thu")) { returnValue = 4; } else if (strWeek.equals("Fri")) { returnValue = 5; } else if (strWeek.equals("Sat")) { returnValue = 6; } else if (strWeek.equals("Sun")) { returnValue = 0; } else if (strWeek == null) { returnValue = 0; } return returnValue; } /** * 獲取日期字串中的中文時間表示字串 * @param strDate * @return */ public static final String getSabreTime(String strDate) { String strReturn = ""; try { Date d = DateUtil.str2Date("yyyy-MM-dd HH:mm:ss", CTool.replace( strDate, "T", " ")); strReturn = DateUtil.date2Str("hh:mm aaa", d); } catch (Exception e) { return strReturn; } return strReturn; } /** * 獲取日期字串中的中文日期表示字串 * @param strDate * @return */ public static final String getSabreDate(String strDate) { String strReturn = ""; try { String p = null; if (strDate.length() > 10) p = "yyyy-MM-dd HH:mm:ss"; else p = "yyyy-MM-dd"; Date d = DateUtil.str2Date(p, CTool.replace(strDate, "T", " ")); strReturn = DateUtil.date2Str("EEE d-MMM", d); } catch (Exception e) { return strReturn; } return strReturn; } /** * 獲取日期字串的中文日期時間表示 * @param strDate * @return */ public static final String getSabreDateTime(String strDate) { String strReturn = ""; try { String p = null; if (strDate.length() > 10) p = "yyyy-MM-dd HH:mm:ss"; else p = "yyyy-MM-dd"; Date d = DateUtil.str2Date(p, CTool.replace(strDate, "T", " ")); strReturn = DateUtil.date2Str("EEE d-MMM hh:mm aaa", d); } catch (Exception e) { return strReturn; } return strReturn; } /** *得到格式化後的指定日期 *@param strScheme 格式模式字串 *@param date 指定的日期值 *@return 格式化後的指定日期,如果有異常產生,返回空串"" *@see java.util.SimpleDateFormat */ public static final String getDateTime(Date date, String strScheme) { String strReturn = null; try { SimpleDateFormat sdf = new SimpleDateFormat(strScheme); strReturn = sdf.format(date); } catch (Exception e) { strReturn = ""; } return strReturn; } /** * 獲取日期 * @param timeType 時間型別,譬如:Calendar.DAY_OF_YEAR * @param timenum 時間數字,譬如:-1 昨天,0 今天,1 明天 * @return 日期 */ public static final Date getDateFromNow(int timeType, int timenum){ Calendar cld = Calendar.getInstance(); cld.set(timeType, cld.get(timeType) + timenum); return cld.getTime(); } /** * 獲取日期 * @param timeType 時間型別,譬如:Calendar.DAY_OF_YEAR * @param timenum 時間數字,譬如:-1 昨天,0 今天,1 明天 * @param format_string 時間格式,譬如:"yyyy-MM-dd HH:mm:ss" * @return 字串 */ public static final String getDateFromNow(int timeType, int timenum, String format_string){ if ((format_string == null)||(format_string.equals(""))) format_string = "yyyy-MM-dd HH:mm:ss"; Calendar cld = Calendar.getInstance(); Date date = null; DateFormat df = new SimpleDateFormat(format_string); cld.set(timeType, cld.get(timeType) + timenum); date = cld.getTime(); return df.format(date); } /** * 獲取當前日期的字串 * @param format_string 時間格式,譬如:"yyyy-MM-dd HH:mm:ss" * @return 字串 */ public static final String getDateNow(String format_string){ if ((format_string == null)||(format_string.equals(""))) format_string = "yyyy-MM-dd HH:mm:ss"; Calendar cld = Calendar.getInstance(); DateFormat df = new SimpleDateFormat(format_string); return df.format(cld.getTime()); } public static String getDatePattern2() { return datePattern2; } public static void setDatePattern2(String datePattern2) { DateUtil.datePattern2 = datePattern2; } /** * 獲得指定日期的前一天日期 * @param currDate * @return */ public static Date getPreviousDate(Date currDate){ Date previousDate = null; try{ Calendar calendar = Calendar.getInstance(); //得到日曆 calendar.setTime(currDate);//把當前時間賦給日曆 calendar.add(Calendar.DAY_OF_MONTH, -1); //設定為前一天 previousDate = calendar.getTime(); }catch(Exception ex){ ex.printStackTrace(); } return previousDate; } /** * 判斷指定日期是否是星期日 * * @param currDate * @return */ public static boolean isSunday(Date currDate){ boolean state = false; try{ }catch(Exception ex){ state = false; ex.printStackTrace(); } return state; } /** * 獲得指定日期所在一週的星期一的日期 * * @param currDate * @return */ public static Date mondayDate(Date currDate){ Date mondayDate = null; try{ }catch(Exception ex){ ex.printStackTrace(); } return mondayDate; } /** * 獲得指定日期所在一週的星期日的日期 * * @param currDate * @return */ public static Date SundayDate(Date currDate){ Date sunday = null; try{ }catch(Exception ex){ ex.printStackTrace(); } return sunday; } /** * 獲得指定日期所在一週在一年中的週數 * * @param currDate * @return */ public static int week(Date currDate){ int weekNum = 0; try{ }catch(Exception ex){ ex.printStackTrace(); } return weekNum; } /** * * 得到某年某周的第一天 * @param year * @param week * @return */ public static Date getFirstDayOfWeek(int year, int week) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.WEEK_OF_YEAR, week); calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 設定週一 calendar.setFirstDayOfWeek(Calendar.MONDAY); return calendar.getTime(); } /** * 得到某年某周的最後一天 * @param year * @param week * @return */ public static Date getLastDayOfWeek(int year, int week) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.WEEK_OF_YEAR, week); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek() + 6); // Sunday return calendar.getTime(); } /** * 獲得指定日期的前一日 * * @return */ public static String getBeforeDate(Date currDate){ //獲得系統日期的前一天 Calendar calendar = Calendar.getInstance(); //得到日曆 calendar.setTime(currDate);//把當前時間賦給日曆 calendar.add(Calendar.DAY_OF_MONTH, -1); //設定為前一天 Date beforeDate = calendar.getTime(); //得到前一天的時間 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String beforeDateStr = sdf.format(beforeDate); return beforeDateStr; } /** * 獲得指定日期的前一月 * * @return */ public static String getBeforeMonth(Date currDate){ //獲得系統日期的前一天 Calendar calendar = Calendar.getInstance(); calendar.setTime(currDate); calendar.add(Calendar.MONTH, -1); //設定為前一月 Date beforeDate = calendar.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); String beforeDateStr = sdf.format(beforeDate); return beforeDateStr; } /** * 取得當前日期對應周的前一週 * * @param date * @return */ public static int getBeforeWeekOfYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.setMinimalDaysInFirstWeek(1); calendar.setTime(date); calendar.add(Calendar.WEEK_OF_YEAR, -1); //設定為前一週 return calendar.get(Calendar.WEEK_OF_YEAR); } /** * 取得當前日期的年份 * * @param date * @return */ public static int getYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setFirstDayOfWeek(Calendar.MONDAY); calendar.setMinimalDaysInFirstWeek(1); Date beforeDate = calendar.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); String beforeDateStr = sdf.format(beforeDate); return Integer.valueOf(beforeDateStr).intValue(); } public static String getDatePattern3() { return datePattern3; } public static String getDatePattern4() { return datePattern4; } public static void setDatePattern4(String datePattern4) { DateUtil.datePattern4 = datePattern4; } /** * 計算兩個日期之間相差的天數 * @param startTime 較小的時間 * @param endTime 較大的時間 * @return 相差天數 * @throws ParseException */ public static int daysBetween(Date startTime,Date endTime) throws ParseException{ SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); startTime=sdf.parse(sdf.format(startTime)); endTime=sdf.parse(sdf.format(endTime)); Calendar cal = Calendar.getInstance(); cal.setTime(startTime); long time1 = cal.getTimeInMillis(); cal.setTime(endTime); long time2 = cal.getTimeInMillis(); long between_days=(time2-time1)/(1000*3600*24); return Integer.parseInt(String.valueOf(between_days)); } }
相關推薦
java date 工具類 DateUtil 格式轉換
package systems.baseutil.tool; /** * <p>Title: 時間和日期的工具類</p> * <p>Description: DateUtil類包含了標準的時間和日期格式,以及這些格式在字串及日期之間
java日期工具類DateUtil-續二
該版本是一次較大的升級,農曆相比公曆複雜太多(真佩服古人的智慧),雖然有規律,但涉及到的取捨、近似的感念太多,況且本身的概念就已經很多了,我在網上也是查閱了很多的資料,雖然找到一些計算的方法,但都有些計算缺陷,後來才終於找到“壽天星文歷”:一個十分精準的萬年曆。雖然它的功能
java Date日期類和SimpleDateFormat日期類格式
常用 tostring 靈活 是否 dem cep sta stat pre ~Date表示特定的時間,精確到毫秒~構造方法:public Date()//構造Date對象並初始化為當前系統的時間public Date(long date) //1970-1-1 0:
java常用工具類(一)—— Map 與 Bean 之間的互相轉換
import net.bytebuddy.implementation.bytecode.Throw; import org.springframework.cglib.beans.BeanMap; import java.beans.PropertyDescriptor; import java.lang
Java 常用工具類---- 各種字符集編碼判斷與轉換
import java.io.UnsupportedEncodingException; /** * 判斷字元編碼 * * @author guyinyihun */ public class CharacterCodingUtil { private final static
java開發中常用的日期時間工具類 DateUtil
java開發中常會用到的 日期時間工具類。 package org.demo; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateForm
java 日期處理工具類 DateUtil
http://bjtdeyx.iteye.com/blog/1551946 Java 日期時間 Date型別,long型別,String型別表現形式的轉換 http://www.xuebuyuan.com/1756921.html
Java時間工具類(把日期時間轉換成xx秒前、xx分鐘前、xx小時前...)
package com.liuzy.javaopen.entity; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;
Java Date時間的處理-Date工具類
package tag; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; i
Java日期工具類
multipl efault 簡體中文 類型 分鐘 sub dateutil 表示 exception public class DateUtil { //默認顯示日期的格式 public static final String DATAFORMAT_ST
java Collections 工具類
ofb read int 交換 個數 frequency sta alt 工具 1.reverse反轉2.shuffle隨機排序3.sort自然排序4.sort指定比較器排序5.swap將下標位置為x和y的元素進行交換6.max 最大值7.min 最小值8.frequenc
開源Java時間工具類Joda-Time體驗
java import org.joda.time.*; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.Test; import java
Java之工具類:判斷對象是否為空或null
sar 判斷 ins == span urn lean color style 1 import java.lang.reflect.Array; 2 import java.util.Collection; 3 import java.util.Map; 4
JAVA StringUtils工具類
eat mov 去除 apache source xtra tab sub one org.apache.commons.lang Class StringUtils java.lang.Object org.apache.commons.lang.St
Date工具類
n) emp catch addm class 工具 eof pan throws java 時間工具類 import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseExcep
java FileUtil工具類
copyfile 部分 ace malformed put 字符 windows final 沒有 網上的版本太多,整合了一下適合自己用的工具類,包括讀取、保存、拷貝文件等。 public class FileUtil { /** * 私有構造方法,防止
強大的Java Json工具類
bsp input ext line bject style shm 工具類 tac 轉自: https://blog.csdn.net/u014676619/article/details/49624165 import java.io.Buffered
Java 常用工具類整理
一、org.apache.commons.io.IOUtils closeQuietly 關閉一個IO流、socket、或者selector且不丟擲異常。通常放在finally塊。 toString 轉換IO流、 Uri、 byte[]為String。
java ExcelUtil工具類List轉Excel,Excel轉List
首先要做一個 通過欄位名稱獲取屬性值 的方法 /** * @MethodName : getFieldValueByName * @Description : 根據欄位名獲取欄位值 * @param fieldName 欄位名 * @param o 物件 * @return 欄位值
Java 常用工具類
PageBaen 分頁工具類 package com.strurts.utli; import java.util.Map; import javax.servlet.http.HttpServletRequest; public class PageBean {