从Date类添加年份 [英] Adding Years from Date class

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

问题描述

假设我有这个:

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

我有一个随机日期,例如05/06/2015(不是固定日期,它随机每次)。如果我想参加这个日期的年份,并在今年添加n,我该怎么做?

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

所有方法日期类不是'int'。

all the methods in Date Class aren't 'int'.

并且要从int添加年份,'years'也必须是int

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

推荐答案

您需要将日期转换为日历

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

您可以将年份(或其他字段)作为日历进行操作,然后将其转换回日期。

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

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

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