I have successfully imported date column from excel to the java code. However, I am unable to change the date format from 17-Dec-2018 to 2018-12-17. Kindly help.
public void saveToDatabase(Vector dataHolder) throws ParseException {
System.out.println(dataHolder);
for(Iterator iterator = dataHolder.iterator();iterator.hasNext();) {
List list = (List) iterator.next();
fullName = list.get(0).toString();
idNumberString = list.get(1).toString();
//idNumber = Integer.parseInt ( idNumberString );
committee = list.get(2).toString();
amountString = list.get(3).toString();
//amount = Integer.parseInt ( amountString );
bosaFosa = list.get(4).toString();
purpose = list.get(5).toString();
paymentsType = list.get(6).toString();
supportingDocuments = list.get(7).toString();
entryDate = list.get(8).toString();
}
The code now after fetching data from excel column the month is in text as "Dec" that is "17-Dec-2018" I expect the final output in string as "2018-12-17" so that I can store in MYSQL database as DATE Type.
Your code is just simple. Here is code:
Parse string input.
Generate string output.
Here
DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH)
is the input date format and locale.Here is the imports:
EDIT: Please follow the answer of @Ole V.V. given above as it is a better solution than mine.
You will first have to convert the
String
data intoDate
object. Example code:Then you can use
SimpleDateFormat
class to format date as you wish.For more details on
SimpleDateFormatter
class, check this outjava.time
The example is a bit simpler than yours, but should answer what you are asking about, so I trust the rest to you. I am using (and warmly recommending) java.time, the modern Java date and time API, for all date work in Java.
The steps involved for the date are:
LocalDate
.LocalDate.parse(entryDateString, dateFormatter)
does this. In the format pattern string,d-MMM-uuuu
d
means day of month in 1 or 2 digits,MMM
means month abbreviation, anduuuu
means 4 digit year. The month abbreviation is locale specific. Since I tookDec
to be English, I have specified English locale for the formatter; please correct if your date strings are in some other language.LocalDate
to yourPreparedStatement
.insertStatement.setObject(3, entryDate);
does this.If you want to check that the first point worked as expected:
Output:
PS You may also want to check whether you can get the date from Excel in a different way. If you are using an older library such as Apache POI, I am afraid that the other option is an old-fashioned
Date
object, which you would then need to convert, so it’s a question whether it’s worth it.Link: Oracle tutorial: Date Time explaining how to use java.time.