HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Convert Integer to Date in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertintegerdatejava

Problem

Due to some clueless soul, we have several fields in a legacy database that uses a 6-digit integer to represent a date in (YYYYmm) format. The date field is assumed to be the last day of the given month.

I have written the following method to perform the conversion from int to java.util.Date:

public Date convertIntToDate(Integer intDate) {

    if (intDate  999999) {
        log.warn("Unable to parse int date {}", intDate);
        return null;
    }

    int intYear = intDate/100;
    int intMonth = intDate - (intYear * 100);

    Calendar result = new GregorianCalendar();
    result.set(intYear, intMonth - 1, 1, 0, 0, 0);

    return result.getTime();
}


It seems to work, but if anyone has any suggested improvements, I'd love to hear them.

Solution

The date field is assumed to be the last day of the given month.

This seems to suggest that you would want to convert 201502 to 2015 Feb 28,
as that's the last day of 2015 Feb.
Your code converts to 2015 Feb 01, I hope that's what you really meant.

Your validation is too weak:

if (intDate  999999) {
    log.warn("Unable to parse int date {}", intDate);
    return null;
}


So, 999999 is a valid date? The method will convert that to 10007-03-01.

What about 201599? The method will convert that to 2023-03-01. Not so great.

I'd suggest to do the validation after converting to intYear and intMonth.
It will be easier to follow and more logical.

Why does the method take an Integer?
It doesn't make sense, and it makes the method prone to NullPointerException.
(The code will throw when reaching intDate < 100000 in the if condition.)

The conversion to month would be more readable with a modulo:

int intMonth = intDate % 100;


And the way you set the month is incorrect,
as the second value of result.set is supposed to be a constant like Calendar.JANUARY.
The correct way:

result.set(Calendar.YEAR, intYear);
    result.set(Calendar.MONTH, intMonth - 1);
    result.set(Calendar.DAY_OF_MONTH, 1);

Code Snippets

if (intDate < 100000 || intDate > 999999) {
    log.warn("Unable to parse int date {}", intDate);
    return null;
}
int intMonth = intDate % 100;
result.set(Calendar.YEAR, intYear);
    result.set(Calendar.MONTH, intMonth - 1);
    result.set(Calendar.DAY_OF_MONTH, 1);

Context

StackExchange Code Review Q#82208, answer score: 7

Revisions (0)

No revisions yet.