1

I have an application that inserts date into a database. When I opened the entries with Eclipse neon in Data Source Explorer, I found that the years in the date have the value "3916"(example: 3916-10-05). Knowing that the variables are of type java.util.date and that the column in the db is of type DATE.

Chayma Atallah
  • 725
  • 2
  • 13
  • 30
  • 1
    Can you share the code which populates the Java dates? – Tim Biegeleisen Jun 16 '17 at 12:33
  • It’s probably the same problem as in [this question: java.util.Date and getYear()](https://stackoverflow.com/questions/9243578/java-util-date-and-getyear), only seen from the opposite side. – Ole V.V. Jun 17 '17 at 07:21

1 Answers1

2

I think this example will help you understand what your real problem is (try it):

import java.util.Date;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Date date = new Date(1475625600000L); //2016-10-05
        int year = date.getYear();
        System.out.println("Year from epoch: " + date.getYear());
        date.setYear(2016);
        System.out.println("Year from setYear() " + date.getYear());
        System.out.println("Full date: " + date.toString());
    }
}

This will print

Year from epoch: 116
Year from setYear() 2016
Full date: Thu Oct 05 00:00:00 GMT 3916

java.util.Date is a bit weird when it comes to handling years in dates. It uses an offset of 1900 when you set years and subtracts it, when you get years from dates.

From the documentation:

getYear()
Deprecated. 
As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.

setYear(int year)
Deprecated. 
As of JDK version 1.1, replaced by Calendar.set(Calendar.YEAR, year + 1900).

If you try setting a year as its 4 digit form, you end up with date after 3900.

Laposhasú Acsa
  • 1,550
  • 17
  • 18
  • Very likely hypothesis, I agree. The real and good solution would be to discard the outdated `Date` and `Calendar` classes completely and use the modern `java.time` API classes instead, like `LocalDate` for example. With a sufficiently new JDBC driver, one can insert these directly into the database. – Ole V.V. Jun 17 '17 at 07:14