我試圖將一個給定的 "持續時間 "添加到當前時間。比如說,
String runtime = "1h58m"
而我正試圖將其添加到當前的時間中,以便輸出看起來像
。
<movie name> 的運行時間是<runtime>。
<Name>將在<calculatedDate>結束。
其中計算的日期是系統的當前時間,lust是給出的運行時間。
這就是我目前的情況,但不知道如何將運行時間添加到系統的當前時間中。
public void playMovie(Movie movie){
SimpleDateFormat df = new SimpleDateFormat("MM/dd/Y hh: MMAA")。)
Date date = new Date()。
System.out.println(" name "的運行時間是" runtime)。
System.out.println("" name "將結束于" df.format(date))。
uj5u.com熱心網友回復:
java.time
java.util日期-時間API和它們的格式化API,SimpleDateFormat已經過時并且容易出錯。建議完全停止使用它們,轉而使用現代的日期-時間 API*。
使用java.time,現代日期-時間 API 的解決方案:我建議你使用java.time.Duration,它是與Java-8一起引入的,是JSR-310實作來模擬ISO_8601#Duration。
演示:
import java.time.Duration。
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args){
String runtime = "1h58m"/span>;
runtime = "PT"/span> runtime;
Duration duration = Duration.parse(runtime)。
System.out.println(duration)。
LocalDateTime now = LocalDateTime.now()。
LocalDateTime endTime = now.plus(duration)。
System.out.println(endTime)。
//自定義格式
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu hh:mm a"/span>, Locale.ENGLISH)。
System.out.println(endTime.format(dtf))。
}
}
輸出:
PT1H58M
2021-09-11T23:03:58.749831。
09/11/2021 11:03 PM
。
從Trail.Date Time API了解更多關于現代日期時間API的資訊。日期時間。
*對一個人來說,他是一個非常重要的人。
* 出于任何原因,如果你必須堅持使用Java 6或Java 7,你可以使用ThreeTen-Backport,它將大部分java.time功能回傳到Java 6 & 7。如果您正在為一個 Android 專案作業,而您的 Android API 水平仍然不符合 Java-8 的要求,請查看通過 desugaring 提供的 Java 8 API 和 如何在 Android 專案中使用 ThreeTenABP。
uj5u.com熱心網友回復: 只要像這樣使用LocalDateTime API(自java 8以來): uj5u.com熱心網友回復: 你可以使用LocalTime類,如下圖所示。
標籤:System.out.println("將結束于" LocalDateTime. now().plusHours(1).plusMinutes(30).plusSeconds(45) )。
public void playMovie(Movie movie){
//從字串的運行時間中找到小時、分鐘和秒
int n = runtime.length()。
int hours = 0;
int minutes = 0;
int seconds = 0;
int i=0;
for(int j=1; j<n; j ){
if(runtime.charAt(j)=='h'/span>){
hours = Integer.parseInt(runtime.substring(i,j))。
i=j 1。
}
if(runtime.charAt(j)=='m'/span>){
minutes = Integer.parseInt(runtime.substring(i,j))。
i=j 1。
}
if(runtime.charAt(j)=='s'/span>){
seconds = Integer.parseInt(runtime.substring(i,j))。
i=j 1。
}
}
//SimpleDateFormat df = new SimpleDateFormat("MM/dd/Y hh:maa");
//Date date = new Date();
System.out.println(" name 的運行時間是" runtime)。
//System.out.println("" name "將結束于 " df.format(date));
//使用LocalTime類的當前系統時間。
LocalTime currentSystemTime = LocalTime.now() 。
//將電影的持續時間添加到當前系統時間中。
LocalTime movieEndTime = currentSystemTime
.plusHours(小時)
.plusMinutes(分鐘)
.plusSeconds(秒)。
System.out.println(" name " 將在" movieEndTime "結束。)
}
