如何通过在java中传递当前日期来获取下一个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22530978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How get next date by passing current Date in java
提问by java baba
How do I get the next date(2014/03/21) given the current date(2014/03/20) in Java?
给定Java中的当前日期(2014/03/20),如何获取下一个日期(2014/03/21)?
Code:
代码:
public static String getNextDate(String curDate) {
String nextDate="";
try {
//here logic to get nextDate
} catch (Exception e) {
return nextDate;
}
return nextDate;
}
采纳答案by SCI
Use SimpleDateFormat to get a Date-object from your string representation, then use Calendar for arithmetics followed by SimpleDateformat to convert the Date-object back to a string representation. (And handle the Exceptions I didn't do)
使用 SimpleDateFormat 从字符串表示中获取日期对象,然后使用 Calendar 进行算术运算,然后使用 SimpleDateformat 将日期对象转换回字符串表示。(并处理我没有做的异常)
public static String getNextDate(String curDate) {
final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
final Date date = format.parse(curDate);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, 1);
return format.format(calendar.getTime());
}
回答by sheu
use java Calendar and you can use to do some date arithmetic such as adding day, months and years
使用java Calendar,你可以用它来做一些日期运算,比如添加日、月和年
public static String getNextDate(String curDate) {
String nextDate = "";
try {
Calendar today = Calendar.getInstance();
DateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = format.parse(curDate);
today.setTime(date);
today.add(Calendar.DAY_OF_YEAR, 1);
nextDate = format.format(today.getTime());
} catch (Exception e) {
return nextDate;
}
return nextDate;
}
回答by StaNov
回答by PMunch
If you want a more native Java way you could split the string using String.split("/") and then add to the date part. However doing this requires that the carry is handled and that you track leap years.
如果您想要更原生的 Java 方式,您可以使用 String.split("/") 拆分字符串,然后添加到日期部分。但是,这样做需要处理进位并跟踪闰年。