java 計算某個時間點(eg: 2018-01-31 10:30:50) 加上幾個月之後對應的時間點
阿新 • • 發佈:2018-11-21
1. 導包:
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;
2. 程式碼:
public static void main(String[] args) throws Exception { //long validatetime = 1517193050L;//29 2018-01-29 10:30:50 //long validatetime = 1517279450L;//30 2018-01-30 10:30:50 long validatetime = 1517365850L;//31 2018-01-31 10:30:50 Date tempDate = new Date(validatetime * 1000); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.err.println("--------" + sdf.format(tempDate)); for (int i = 1; i <= 31; i++) { Calendar calendar = Calendar.getInstance();calendar.setTime(tempDate); calendar.add(Calendar.MONTH, i); System.err.println("--------======" + calendar.getTimeInMillis() / 1000); System.err.println("--------------======" + sdf.format(calendar.getTime())); } }
3. 時間戳例子對應的輸出結果如下,閏年、2月等特殊時間點,cover無誤:
--------2018-01-31 10:30:50 --------======1519785050 --------------======2018-02-28 10:30:50 --------======1522463450 --------------======2018-03-31 10:30:50 --------======1525055450 --------------======2018-04-30 10:30:50 --------======1527733850 --------------======2018-05-31 10:30:50 --------======1530325850 --------------======2018-06-30 10:30:50 --------======1533004250 --------------======2018-07-31 10:30:50 --------======1535682650 --------------======2018-08-31 10:30:50 --------======1538274650 --------------======2018-09-30 10:30:50 --------======1540953050 --------------======2018-10-31 10:30:50 --------======1543545050 --------------======2018-11-30 10:30:50 --------======1546223450 --------------======2018-12-31 10:30:50 --------======1548901850 --------------======2019-01-31 10:30:50 --------======1551321050 --------------======2019-02-28 10:30:50 --------======1553999450 --------------======2019-03-31 10:30:50 --------======1556591450 --------------======2019-04-30 10:30:50 --------======1559269850 --------------======2019-05-31 10:30:50 --------======1561861850 --------------======2019-06-30 10:30:50 --------======1564540250 --------------======2019-07-31 10:30:50 --------======1567218650 --------------======2019-08-31 10:30:50 --------======1569810650 --------------======2019-09-30 10:30:50 --------======1572489050 --------------======2019-10-31 10:30:50 --------======1575081050 --------------======2019-11-30 10:30:50 --------======1577759450 --------------======2019-12-31 10:30:50 --------======1580437850 --------------======2020-01-31 10:30:50 --------======1582943450 --------------======2020-02-29 10:30:50 --------======1585621850 --------------======2020-03-31 10:30:50 --------======1588213850 --------------======2020-04-30 10:30:50 --------======1590892250 --------------======2020-05-31 10:30:50 --------======1593484250 --------------======2020-06-30 10:30:50 --------======1596162650 --------------======2020-07-31 10:30:50 --------======1598841050 --------------======2020-08-31 10:30:50