一、獲取當前時間及未來時間
1 package com.alipay.ipay.gn.commontool; 2 3 import org.testng.annotations.Test; 4 5 import java.text.SimpleDateFormat; 6 import java.util.Calendar; 7 import java.util.Date; 8 import java.util.GregorianCalendar; 9 10 /** 11 * @author 12 * @version 1.0 13 * @time 2019/12/1 16:59 14 */ 15 public class GetDate { 16 /** 17 * 獲取當天日期 18 * 19 * @param dateFormat 日期格式(yyyy-MM-dd HH:mm:ss) 20 * @return 21 */ 22 public static String getNowDate(String dateFormat) { 23 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); 24 String nowDate = simpleDateFormat.format(new Date()); 25 26 return nowDate; 27 } 28 29 /** 30 * 獲取當天后的第n天日期 31 * 32 * @param dateFormat 日期格式(yyyy-MM-dd HH:mm:ss) 33 * @param futureCount 34 * @return 35 */ 36 public static String getFutureDate(String dateFormat, int futureCount) { 37 SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); 38 39 Calendar calendar = new GregorianCalendar(); 40 calendar.setTime(new Date()); 41 calendar.add(calendar.DATE, futureCount); 42 String futureDate = simpleDateFormat.format(calendar.getTime()); 43 44 return futureDate; 45 } 46 47 @Test 48 public void testGetNowDate() { 49 System.out.println(getNowDate("yyyy-MM-dd HH:mm:ss")); // 2019-12-11 21:04:44 50 System.out.println(getNowDate("yyyyMMdd")); // 20191211 51 System.out.println(getNowDate("yyyyMMddHHmmss")); // 20191211210444 52 System.out.println(getNowDate("yyyyMMddHHmmssSSS")); // 20191211210444619 53 } 54 55 @Test 56 public void testGetFutureDate() { 57 System.out.println(String.format("今天后的第%s天是:%s", 2, getFutureDate("yyyy-MM-dd", 2))); // 今天后的第2天是:2019-11-29 58 } 59 60 }
擴展:
System.currentTimeMillis()

二、日期、數字互轉
/** * 功能:數字格式的日期裝換為指定格式的日期 * * @param longDate 數字格式的日期 (如:1477843200000) * @param dateFormat 轉換后的日期格式 (如:yyyy-MM-dd) * @return */ public static String longDateToDate(String longDate, String dateFormat) { Date date = new Date(Long.parseLong(longDate)); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); return simpleDateFormat.format(date); } /** * 功能:指定格式的日期轉換為數字格式的日期 * * @param date 日期 * @param dateFormat 日期格式 * @return */ public static long dateToLongDate(String date, String dateFormat) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); try { long time = simpleDateFormat.parse(date).getTime(); return time; } catch (ParseException e) { e.printStackTrace(); } return -1; }
輸出:
2019-11-14
1573660800000
三、獲取當前時間戳(long類型)
public static long getNowLongDate(int length) { // 獲取13位時間戳(單位毫秒) if (length == 13) { return System.currentTimeMillis(); } // 獲取10位時間戳(單位秒) if (length == 10) { return System.currentTimeMillis() / 1000; } return 0; } public static void main(String[] args) { System.out.println(getNowLongDate(10)); System.out.println(getNowLongDate(13)); }
輸出:
1586791104
1586791104262
