如何在Java中为日期添加天数 [英] How to add days to a date in Java

查看:45
本文介绍了如何在Java中为日期添加天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在日期中添加天数以获取 Java 中的新日期.如何使用 Calendar 类实现它.

I want to add days to a date to get a new date in Java. How to achieve it using the Calendar class.

Calendar dom = new GregorianCalendar(d, m, y);

是我的制造日期的实例,我想在当前日期的基础上增加大约 100 天,并将其存储在变量 doe 中,但无法做到这一点.>

is the instance of my date of manufacture and I want to reach to date of expiry adding some 100 days to the current date and store it in a variable doe but unable to do that.

推荐答案

利用 Calendar#add().这是一个启动示例.

Make use of Calendar#add(). Here's a kickoff example.

Calendar dom = Calendar.getInstance();
dom.clear();
dom.set(y, m, d); // Note: month is zero based! Subtract with 1 if needed.
Calendar expire = (Calendar) dom.clone();
expire.add(Calendar.DATE, 100);

如果您想要更大的灵活性和更少冗长的代码,我建议您使用 JodaTime.

If you want more flexibility and less verbose code, I'd recommend JodaTime though.

DateTime dom = new DateTime(y, m, d, 0, 0, 0, 0);
DateTime expire = dom.plusDays(100);

这篇关于如何在Java中为日期添加天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆