开发者

Java decimal to date value

I'm attempting something and I'm not quite sure how to approach it. I have two user defined values.....a duration and a duration unit. At this point I will already have a start date, so I want to apply the duration and durationUnit somehow to startDate to get the endDate.

Duration is a decimal, durationUnit a HardCode/AbstractCode value and startDate is a Date.

So if the startDate is 17/12/2010......and th开发者_运维问答e user enters the following;

Duration: 3 Duration Unit: Months

I want the endDate to then be calculated as 17/03/2011. Any idea on how I could do this? The duration unit could be Days, Months or Years.

Thanks in advance!


Have a look at joda-time. It's a superb replacement for Date/Calendar. You can do things like:

DateTime newDate = startDate.plusDays(days);
                            .plusYears(years);

Period toAdd = periodFormatter.parse(inputString);
DateTime newDate = startDate.plus(toAdd);


You can map the Day/Month/Year to the appropriate Calendar DAY, MONTH or YEAR. Then use calendar.add(). If by decimal you mean a double then you will probably have to do some processing to turn parts of a value into appropriate values (such as changing .5 DAY to 12 hours).


DateFormatter is also of use if you want a date to be represented in different styles. Here, for the sake of brevity, the methods are invoked on classes which you should instatiate first whether using a factory or a constructor. The following statements are only for grasping the idea. Consult JavaDoc API for further details.


Calendar.set(...) //(to set year, month and day).
Calendar.add(...)//(to add a value on specific unit (month, day or year))
Calendar.getInstance() //(return Date object)
DateFormat.format(..) //(return a String representing a style used at instantiation of //DateFormat)


Haven't you tried using the Date type

Date myDate = new Date();
myDate.setMonth();
myDate.setDay();

I haven't use it myself, so i can really, tell you i f it really works, but you shoul give it a try


Others said it already, here a more concrete sample using java.util.Calendar:

Calendar cal = Calendar.getInstance();
cal.setTime(startDate);

if(durationUnit.equals("day")){
   cal.add(Calendar.DATE, duration);
} else if(durationUnit.equals("month")){
   cal.add(Calendar.MONTH, duration);
} else if(durationUnit.equals("year")){
   cal.add(Calendar.YEAR, duration);
}

Date endDate = cal.getTime();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜