从Date类向随机日期添加Years [英] Adding Years to a random date from Date class

查看:54
本文介绍了从Date类向随机日期添加Years的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有这个:

 PrintStream out = System.out;
 Scanner in = new Scanner(System.in);
 out.print("Enter a number ... ");
 int n = in.nextInt();

我有一个随机日期,例如2015年5月6日(这不是固定日期,每次都是随机的).如果我想取这个日期的年份",并在今年加上"n",我该怎么做?

I have a random date, for example, 05/06/2015 (it is not a fixed date, it is random every time). If I want to take the 'year' of the this date, and add whatever 'n' is to this year, how do i do that?

Date类中的所有方法都不是'int'.

None of the methods in the Date Class are 'int'.

要从一个整数中添加年份,"years"也必须是一个整数.

And to add years from an int, 'years' has to be an int as well.

推荐答案

您需要将 Date 转换为 Calendar .

Calendar c = Calendar.getInstance();
c.setTime(randomDate);
c.add(Calendar.YEAR, n);
newDate = c.getTime();

您可以将Year(或其他字段)用作日历,然后将其转换回Date.

You can manipulate the Year (or other fields) as a Calendar, then convert it back to a Date.

这篇关于从Date类向随机日期添加Years的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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