converting date format

后端 未结 5 1433
我寻月下人不归
我寻月下人不归 2020-12-04 03:00

I got date as \'14-Dec-2010\' i want to get the month in number format for the given date. that is., i want to convert the date to \'14-12-2010\'.<

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 03:56

    Avoid using the troublesome old date-time classes bundled with the earliest versions of Java. They are poorly designed and confusing.

    java.time

    The old classes are supplanted by the java.time framework.

    For a date-only value without time of day and without time zone use LocalDate class.

    Parse the String input using DateTimeFormatter.

    String input = "14-Dec-2010";
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MMM-yyyy" );
    LocalDate localDate = LocalDate.parse( input , formatter );
    

    To generate a String in another format, define another formatter.

    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern( "dd-MM-yyyy" );
    String output = localDate.format( formatter2 );
    

    Better yet, let DateTimeFormatter automatically localize.

    Locale l = Locale.CANADA_FRENCH ;  // Or Locale.US, Locale.ITALY, etc.
    DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( l );
    String output = localDate.format( f );  // Generates String in a localized format.
    

    SQL

    For SQL just pass objects, do not use strings. Pass LocalDate via setObject on a PreparedStatement if your JDBC driver complies with the JDBC 4.2 spec.

    myPrepStmt.setObject( localDate );
    

    If not, fall back to the old java.sql.Date class by using new conversion methods added to the old classes.

    java.sql.Date sqlDate = java.sql.Date.from( localDate );
    myPrepStmt.setDate( sqlDate );
    

提交回复
热议问题