問題描述
我應該如何將 120 天添加到我使用簡單日期格式獲得的當前日期?
How should I add 120 days to my current date which I got using simple date format?
我看過一些關于它的帖子,但無法讓它發揮作用,
I have seen few posts about it but couldn't get it to work,
我的代碼如下:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
//get current date time with Date()
Date date = new Date();
我需要使用 Calendar
庫還是只使用簡單的日期格式?
Do I need to use the Calendar
library or can I just do it with simple date format?
推薦答案
基本上,您可以簡單地使用 Calendar
,它能夠根據更改自動滾動日期的各個字段例如單個字段...
Basically, you can simple use a Calendar
which has the capacity to automatically roll the various fields of a date based on the changes to a single field, for example...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 120);
date = cal.getTime();
仔細查看 日歷
了解更多詳情.
Take a closer look at Calendar
for more details.
是的,有一種使用 Joda Time 的方法,但我可以更快地輸入這個示例;)
Yes, there is a way to do this using Joda Time, but I could type this example quicker ;)
更新 JodaTime 示例
以下是使用 JodaTime 的示例.您可以直接使用 JodaTime 解析 String
值,但既然您已經這樣做了,我就不打擾了...
The following is an example using JodaTime. You could parse the String
value directly using JodaTime, but since you've already done that, I've not bothered...
Date date = ...;
DateTime dt = new DateTime(date);
dt = dt.plusDays(120);
date = dt.toDate();
這篇關于如何在java簡單日期格式中添加天數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!