java 如何在没有日历的情况下向日期添加月份?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4882924/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:26:58  来源:igfitidea点击:

how to add months to the date without Calendar?

javagwtdate

提问by Naoj

I'm now developing gwt project that want to add month to the given date. gwt doesn't support Calendar class so how can I do this ? Date is in "dd.MM.yyyy"format

我现在正在开发想要在给定日期添加月份的 gwt 项目。gwt 不支持 Calendar 类,所以我该怎么做?日期是"dd.MM.yyyy"格式

public Date addMonth(Date d, int months){
}

mine implementation is so long that I need help. Thanks

我的实施时间太长了,我需要帮助。谢谢

[EDIT]

[编辑]

addMonth() means just add months to the given date's month. If it is 01.06.2010adding 4 months is 01.10.2010

addMonth() 表示只在给定日期的月份添加月份。如果01.06.2010增加 4 个月是01.10.2010

for 31 Jan and add 1 it will 28. Feb

1 月 31 日加上 1 将是 28. 二月

回答by Naoj

you can use CalendarUtil

你可以使用 CalendarUtil

import com.google.gwt.user.datepicker.client.CalendarUtil;
...
// Now
Date d = new Date();
// Now + 2 months
CalendarUtil.addMonthsToDate(d, 2);

回答by CoolBeans

How about this? Ofcourse you will have to refine this based on how many days in a month and stuff but you get the basic idea. I am not familiar with gwt but I assumed it doesn't support joda time.

这个怎么样?当然,您必须根据一个月中的天数等来完善它,但您会了解基本概念。我不熟悉 gwt,但我认为它不支持 joda 时间。

This is a rather crude solution. But without using the Calendar class or joda-time this is the only way I can think of for now.

这是一个相当粗糙的解决方案。但是不使用 Calendar 类或 joda-time 这是我现在能想到的唯一方法。

        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy"); //today is 02.02.2011
        Date baseDate = null;
        try {
            baseDate = df.parse(df.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long oneMonthTime = baseDate.getTime()+30*24*60*60; //30 should change based on which month you are on
        System.out.println(df.format(oneMonthTime)); //prints 03.02.2011