开发者

How to write a method that returns number (int) of days from provided day to the todays date?

Please help me to write a method that returns number (int) of days from a provided day to the todays date.

So let's say, I am providing into a method an int 110515 (for May 15, 2011). It should return 9 (inclusive or exclusive is not impor开发者_开发技巧tant to me).


If you can use Joda, this is super simple:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

Of course you could combine these.

int days = Days.daysBetween(startDate, endDate).getDays();

Joda objects can go back and forth between the JDK's date class pretty easily.

For the first part, make a DateFormatter then parse the string based on it, like this:

DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
DateTime dt = fmt.parseDateTime(strInputDateTime);

(After turning the int into a string of course.)


Should dates in the future include the current day? Meaning if today is May 24th 2011, should 110529 result in 4 or 5?

public static long numberOfDays(final long date) throws ParseException {
    final Calendar compare = Calendar.getInstance();
    compare.setTime(new SimpleDateFormat("yyMMdd").parse(String.valueOf(date)));
    final int dstOffset = compare.get(Calendar.DST_OFFSET);
    final long currentTimeMillis = System.currentTimeMillis();
    final long compareTimeInMillis = compare.getTimeInMillis();
    long difference = 0;
    if (currentTimeMillis >= compareTimeInMillis) {
        difference = currentTimeMillis - compareTimeInMillis - dstOffset;
    } else {
        difference = compareTimeInMillis - currentTimeMillis + dstOffset;
    }
    return difference / (24 * 60 * 60 * 1000);
}


Since this seems like a homework question I will help you out. You will want to use Calendar.getTimeInMillis. Then you will want to create a constant that is NUMBER_OF_MILLIS_IN_DAY . From there you subtract the initialDate from the currentDate (both time in millis) and divide by the constant.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜