MaheshVarma
MaheshVarma

Reputation: 2125

Formatting java.sql.Date to yyyyMMdd

I am using the below code

@SuppressWarnings("deprecation")
Date d = new Date (2014,01,9);
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
final String text = df.format(d);
System.out.println(text);

I am getting below output.

3914-02-09
39140209

Does any one know why there is 3914?

Thanks, Mahesh

Upvotes: 2

Views: 2575

Answers (2)

Ankur Singhal
Ankur Singhal

Reputation: 26067

From Java Docs,

Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).

Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments. 

Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.

Code

public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int year = 2014;
        int month = 01;
        int day = 9;
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        cal.set(Calendar.DAY_OF_MONTH, day);

        java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
        System.out.println(sdf.format(date));
    }

output

2014-01-09

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201437

The javadoc for the constructor you're using java.sql.Date(int,int,int) reads (in part),

year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)

so you should use (assuming you mean this year)

Date d = new Date (2015-1900,01,9); 

Upvotes: 2

Related Questions