JAVA獲取當前時間和將已有的long型別時間轉換為年月日時分秒格式
阿新 • • 發佈:2019-02-07
程式碼如下:
public class DateUtil { /** * 根據格式獲取當前格式化時間 * @param format 格式化方式,基礎格式為yyyy-MM-dd HH:mm:ss * @return 當前時間 */ public static String getCurrentTimeByFormat(String format) { SimpleDateFormat df = new SimpleDateFormat(format); return df.format(new Date()); } /** * 格式化時間 * @param format 格式化格式,基礎格式為yyyy-MM-dd HH:mm:ss * @param currentTime * @return */ public static String formatTime(String format, long time) { SimpleDateFormat df = new SimpleDateFormat(format); return df.format(new Date(time)); } }
獲取當前時間的年月日時分秒格式字串:
首先將當前時間轉換為十二小時制的年/月/日 時:分:秒 格式,輸入的格式為yyyy/MM/dd hh:mm:ss
:
public static void main(String[] args) {
String time = DateUtil.getCurrentTimeByFormat("yyyy/MM/dd hh:mm:ss");
System.out.println(time);
}
結果為:2018/09/19 11:08:26
換位二十四小時制,則輸入引數yyyy/MM/dd HH:mm:ss
:
public static void main(String[] args) { String time = DateUtil.getCurrentTimeByFormat("yyyy/MM/dd HH:mm:ss"); System.out.println(time); }
執行輸出結果為2018/09/19 23:09:51
;
如只想要年月日,則入參為yyyy/MM/dd
:
public static void main(String[] args) {
String time = DateUtil.getCurrentTimeByFormat("yyyy/MM/dd");
System.out.println(time);
}
輸出結果為2018/09/19
;
同理只要時分秒則入參為HH:mm:ss
,可以根據需要靈活配置,左斜槓/
可以換為-
等符號或者乾脆不要,時分秒中的:
同理;
轉換long型別時間
測試:
public static void main(String[] args) { String time = DateUtil.formatTime("yyyy-MM-dd HH:mm:ss", 1527320060036L); System.out.println(time); }
結果:
2018-05-26 15:34:20
結果正常,format引數一樣可以自己定義;