Take int of day, month, year and convert to DD/MM/YYYY

后端 未结 2 1858
温柔的废话
温柔的废话 2021-01-29 15:53

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 form

相关标签:
2条回答
  • 2021-01-29 16:29

    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.

    0 讨论(0)
  • 2021-01-29 16:40

    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 );
    
    0 讨论(0)
提交回复
热议问题