-4

I am writing a method to take a DOB of 3 integers - day, month, year and return the formatted version DD/MM/YYYY.

I am currently using dateFormatter and simple date format. Although when I run this it defaults to 01/01/1970 and I cannot change the date.

Any suggestions?

Update

Guys thanks for the below posts, problem solved!

  • A DateFormat is used to format instances of java.util.Date. Not an integer. BTW, there is now way to find out the day, month and year parts of a number obtained by summing these 3 parts. Use a LocalDate: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#of-int-int-int- – JB Nizet Apr 01 '17 at 13:17

2 Answers2

1

Why use formatter? just do this:

   public String DateOfBirth(int day, int month, int year) 
{
    String DOB = day + "/" + month + "/" + year;

    return DOB;
}

If it's for an assignment, the teacher probably wants you to not use formatter.

Also, as someone else mentioned: If you are trying to concatenate integers as a string you need some string in between. Otherwise you are summing the values of the integers.

Noel Murphy
  • 1,264
  • 1
  • 8
  • 12
  • This will give you one-digit day and month if less than 10, for example, 2/4/2017. I understood the question as asking for two digits, like 02/04/2017. If your assumption about avoiding standard classes is correct (which I hope not), you may use `String.format()`. – Ole V.V. Apr 02 '17 at 07:22
1

tl;dr

LocalDate.of( 2017 , 1 , 23 )
         .format( DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )

23/01/2017

java.time

The modern way uses the java.time classes.

Avoid the old legacy date-time classes such as Date and Calendar as they are poorly designed, confusing, troublesome, and flawed.

LocalDate

LocalDate represents a date-only value without time-of-day and without time zone. Note that unlike the legacy classes, here the months have sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 2017 , 1 , 23 );

DateTimeFormatter

Generate a String representing that value by using a formatter object.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );

String output = ld.format( f );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154