I have date column in excel, but when I'm reading in my java application I'm getting value as number
Example
Excel Date
1/1/2013
Am getting as
41275.00
How to convert number to date in my Java application?
I have date column in excel, but when I'm reading in my java application I'm getting value as number
Example
Excel Date
1/1/2013
Am getting as
41275.00
How to convert number to date in my Java application?
Excel’s serialized dates are the number of days since 1/1/1900. In order to figure out the date again, we have to add the serial number worth of days.
for Java 8 without any dependency
```
```
Here is a minimal working example how to convert an Excel date to a Java date:
which returns
You also need to import the following packages:
Apache POI has some utilities for that http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DateUtil.html, notably http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/DateUtil.html#getJavaDate(double)
Note Excel stores dates as the number of days (plus fractional days) since 1900 (and in some cases it can be from 1904). See http://support.microsoft.com/kb/180162.
tl;dr
Use modern java.time classes.
java.time
The modern solution uses the java.time classes that supplanted the terrible legacy date-time classes bundled with the earliest versions of Java.
Epoch reference date: 1899-12-30
According to this documentation, that value from Microsoft Excel is the number of days since the epoch reference of 1900-01-01 in UTC. Internally, the actual reference date is December 30, 1899 as documented on this Wikipedia page.
Beware, some versions (old versions for macOS?) of Excel use a different epoch in 1904.
Establish the epoch reference somewhere in your code.
Do the math
Parse your input string as a
BigDecimal
for accuracy (versus floating-point types that trade away accuracy for faster execution).Add the number of whole days to the epoch reference date.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for
java.sql.*
classes.Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.