Charl Potgieter
Charl Potgieter

Reputation: 211

Creating a new date in Java using ints

I am currently using a Date Picker, to display/select a date. I am just having trouble with the format. below is how the example constructed it.

 new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" ").toString();

I don't want this format so I tried the following but it keeps giving the incorrect year even if the values are correct so I am not sure what I am doing wrong.

SimpleDateFormat dateFormat = new SimpleDateFormat("d MMMM yyyy");
Date date = new Date(year,month,day);
dates.setText(dateFormat.format(date));

for example if the date was 6 November 2015(current date) and I change it to 6 December 2015 it will display 6 December 3915 The following values are being returned year = 2015 month = 11 day = 6 And this Creates 6 December 3915 I don't understand why the year is not displaying properly if I choose 2016 it would be 3916

Upvotes: 1

Views: 565

Answers (2)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22264

This behaviour can be expected actually. This is what the documentation says about the Date constructor you are using (emphasis added by me):

public Date(int year, int month, int day)

Deprecated. instead use the constructor Date(long date)
Constructs a Date object initialized with the given year, month, and day.

The result is undefined if a given argument is out of bounds.

Parameters: year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
month - 0 to 11
day - 1 to 31

So you get 3915 because 2015 + 1900 = 3915

I recommend you don't use this constructor. First of all it is marked as deprecated. Most importantly, no person in his right mind would see an argument int year in a method and think "Of course I have to subtract 1900 from the value I pass"

The LocalDate introduced in Java 8 is recommended as a replacement. You would use it like this

DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd MMMM yyyy");
LocalDate date = LocalDate.of(2015, Month.NOVEMBER, 6);
dates.setText(dateFormat.format(date));

Upvotes: 2

Waddah Ajaj
Waddah Ajaj

Reputation: 141

the format you are using is wrong. try this instead:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM YYYY");

Upvotes: 0

Related Questions