java中Date類和Strng類的靈活轉(zhuǎn)化
在java開發(fā)的實(shí)際場景中,我們經(jīng)常要對時(shí)間進(jìn)行格式化處理,但是每次獲取開發(fā)中自己需要的格式都要重新寫一個(gè)方法,這樣的代碼看起來是非常的笨重并且冗余,為此通過以下的方法可以靈活的對時(shí)間進(jìn)行Date類型和String類型進(jìn)行轉(zhuǎn)化:
話不多說,直接上代碼!
先定義一個(gè)獲取時(shí)間格式的枚舉類
```//首先定義一個(gè)枚舉類public enum DateFormatEnum{ //年份 Y('yyyy'), //年月 YM('yyyy-MM'), //年月日 YMD('yyyy-MM-dd'), //年月日時(shí) YMDH('yyyy-MM-dd HH'), //年月日時(shí)分 YMDHM('yyyy-MM-dd HH:mm'), //年月日時(shí)分秒 YMDHMS('yyyy-MM-dd HH:mm:ss'); private String dataFormatType; //構(gòu)造函數(shù) DateFormatEnum(String dataFormatType){ this.dataFormatType=dataFormatType; } //外部調(diào)用時(shí)間格式類型 String getDataFormatType(){ return this,dataFormatType; } }
再寫一個(gè)簡單的工具類方法就可以讓時(shí)間靈活在Date類和String類上靈活轉(zhuǎn)化了
public class DateUtil{ //Date類轉(zhuǎn)換為String類(任意格式) public static String changeDateToStr(Date date,DateFormatEnum dataFormatEnum){ SimpleDateFormat format = new SimpleDateFormat(dateFormatEnum.getDateFormatType); return format.format(date) } //String類轉(zhuǎn)換為Date類(任意格式) public static Date changeStrToDate(String date,DateFormatEnum dateFormatEnum){ SimpleDateFormat format = new SimpleDateFormat(dateFormatEnum.getDateFormatType); return format.parse(date); } //獲取當(dāng)前時(shí)間的String類型(任意格式) public static String getStrNowDate(DateFormatEnum dateFormatEnum){ SimpleDateFormat format = new SimpleDateFormat(dateFormatEnum.getDateFormatType); return format.format(new Date()) } //獲取當(dāng)前時(shí)間的Date類型(任意格式) public static Date getDateNowDate(DateFormatEnum dateFormatEnum){ SimpleDateFormat format = new SimpleDateFormat(dateFormatEnum.getDateFormatType); return format.parse(new Date()) }}
到此這篇關(guān)于java中Date類和Strng類的靈活轉(zhuǎn)化的文章就介紹到這了,更多相關(guān)java Date類和Strng類轉(zhuǎn)化內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. IntelliJ IDEA導(dǎo)入jar包的方法2. SSM框架JSP使用Layui實(shí)現(xiàn)layer彈出層效果3. 刪除docker里建立容器的操作方法4. IntelliJ IDEA導(dǎo)出項(xiàng)目的方法5. java使用xfire搭建webservice服務(wù)的過程詳解6. .Net中的Http請求調(diào)用詳解(Post與Get)7. JS如何在數(shù)組指定位置插入元素8. PHP下對緩沖區(qū)的控制9. Vue 實(shí)現(xiàn)對quill-editor組件中的工具欄添加title10. Java源碼解析之ClassLoader
