Java/Excel integration, Reading in Dates
For those who have attempted to intergrate Java and Excel for projects or work, this may or may not be useful for you.
Depending on the library you use to read and minipulate the Excel documents, you may or may not have support for reading in dates from Excel. This is because Excel doesn't store the dates as dates, but rather as a counter for the number of days past January, 1, 1900. So, if you have a cell formatted for dates and you read in something like January 2003, you will get 37622. That is not helpful, and you can't just count up the years because you need to take account of leap years. So I wrote a method to figure this out for me (and used a second method I found online to figure out leap years). This was written for my needs, so it doesnt return the day of the month, but it will return the first three letters of the Month, a space, and every digit of the year. If you wanted, getting the day of the month would just be matter of adding to the output, as it's basically computed anyway.
May not be the most efficient matter, but it gets the job done and I've checked it multiple times.
Code Java:
public String getDate(int n)
{
String output = "";
String[] arr1 = new String[]{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
String[] arr2 = new String[]{"31","28","31","30","31","30","31","31","30","31","30","31" };
int year = 1900;
System.out.println(year);
while(n>366)
{
if(isLeapYear(year))
{
n-=366;
year++;
}
else
{
n-=365;
year++;
}
System.out.println(year);
}
if(!isLeapYear(year) && n>365)
{
System.out.println(year);
n-=365;
year++;
}
int i=0;
int tempN=Integer.parseInt(arr2[i+1]);
if(isLeapYear(year) && tempN==28)
tempN=29;
while(n>tempN)
{
int num = Integer.parseInt(arr2[i]);
if(i==1 && isLeapYear(year))
num++;
n-=num;
i++;
if(i!=11)
{
tempN = Integer.parseInt(arr2[i+1]);
if(isLeapYear(year) && tempN==28)
tempN=29;
}
}
output = arr1[i]+" "+year;
return output;
}
public boolean isLeapYear(int theYear)
{
// Is theYear Divisible by 4?
if (theYear % 4 == 0)
{
// Is theYear Divisible by 4 but not 100?
if (theYear % 100 != 0)
return true;
// Is theYear Divisible by 4 and 100 and 400?
else if (theYear % 400 == 0)
return true;
// It is Divisible by 4 and 100 but not 400!
else
return false;
}
return false;
}