java 給時間增加時間得到一個新的時間(日期)


SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd")

LocalDate expirationDate
String expirDate="0"
Date date = df.parse(expirationDate as String) // 指定日期
expirDate = addDate(date, im.expiry2y).format("yyyy-MM-dd")  // 指定日期加上天數
得到一個新的日期
/**
* 效期增加天數,得到一個新的日期
* @param date
* @param day
* @return
* @throws Exception
*/
static Date addDate(Date date,long day) throws Exception {
long time = date.getTime(); // 得到指定日期的毫秒數
day = day*24*60*60*1000; // 要加上的天數轉換成毫秒數
time+=day; // 相加得到新的毫秒數
return new Date(time); // 將毫秒數轉換成日期
}


下面代碼是給日期年數增加年的時間
                        //把LocalDate 轉date
ZoneId zoneId = ZoneId.systemDefault()
ZonedDateTime zdt = exdm.expirationDate.atStartOfDay(zoneId)
//給年數加兩年
Calendar rightNow = Calendar.getInstance()
rightNow.setTime(Date.from(zdt.toInstant()))
rightNow.add(Calendar.YEAR, 2)//給年數增加兩年,得到一個新的日期
expirDate = df.format(rightNow.getTime())




SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd")
Integer daysToExpire=180
Integer warnShelfLife = 60 // 臨期天數
if (isValidDate(batchPart)) {//判斷時間格式是否正確
formatter.setLenient(false)
Date newDate = formatter.parse(batchPart)
formatter = new SimpleDateFormat("yyyy-MM-dd")
String ds = formatter.format(newDate)
Date d = formatter.parse(ds)
expirDate = df.format(new Date(d.getTime() + ((im.daysToExpire ?: 0) - (im.warnShelfLife ?: 0)) * 24 * 60 * 60 * 1000L)) as String

}
結果得到一個新的日期
/**
* 判斷日期格式是否正確
* @param str
* @return
*/
static boolean isValidDate(String str) {
boolean convertSuccess = true
// 指定日期格式為四位年/兩位月份/兩位日期,注意yyyy/MM/dd區分大小寫;
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd")
try {
// 設置lenient為false.
// 否則SimpleDateFormat會比較寬松地驗證日期,比如2007/02/29會被接受,並轉換成2007/03/01
format.setLenient(false)
format.parse(str)
} catch (Throwable t) {
convertSuccess = false
}
return convertSuccess
}

===========================================================以下是網上找到的方法=======================================================
package com.date.test;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Test {

public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
Date date = dateFormat.parse("2015-07-31"); // 指定日期
Date newDate = addDate(date, 20); // 指定日期加上20天
System.out.println(dateFormat.format(date));// 輸出格式化后的日期
System.out.println(dateFormat.format(newDate));
}


public static Date addDate(Date date,long day) throws ParseException {
 long time = date.getTime(); // 得到指定日期的毫秒數
 day = day*24*60*60*1000; // 要加上的天數轉換成毫秒數
 time+=day; // 相加得到新的毫秒數
 return new Date(time); // 將毫秒數轉換成日期
}
}





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM