-2

I have CSV data to import into data base where I have date column in that CSV in that some dates are like 1-DEC-16 without a leading zero (padding zero). How to make that String as 01-DEC-2016? Can it be done with SimpleDateFormat or is there any String format method? I tried with below but it’s not happening.

String d="1-DEC-17";

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(newstring);
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
bharathRaj
  • 25
  • 8

1 Answers1

0

d vs dd

To parse a string with a leading zero on the month or day-of-month, use a pair of formatting pattern characters. That would be dd for day-of-month.

To parse a string without a leading zero, use a single character, d for day-of-month.

Unfortunately, your input has the month name abbreviation in all uppercase. That violates the norm of the English-speaking locales I know of, such as Locale.US. So by default, a DateTimeFormatter will refuse to process that improper input. To tolerate the all-uppercase, we can set the formatter to be “lenient”.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "d-MMM-uu" , Locale.US ).withResolverStyle( ResolverStyle.LENIENT )  ;
LocalDate ld = LocalDate.parse( "1-DEC-17" , f ) ;

See this code run live at IdeOne.com.

ld.toString(): 2017-12-01

If sending this value to a database, do not use a string for date-time value. Use a date-time object for date-time values.

For JDBC drivers compliant with JDBC 4.2 and later, pass the java.time types directly via setObject & getObject.

myPreparedStatement.setObject( … , ld ) ;

If not compliant, convert briefly to the troublesome old legacy type, java.sql.Date. Use the new methods added to the old classes.

java.sql.Date d = java.sql.Date.valueOf( ld ) ;
myPreparedStatement.setDate( … , d ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154