I'm trying to convert a string date to a an object date. It works perfectly if i use a string, but when i read the string date from a file, the result is ko. On forums, i have found the cause may come from zone. It is still KO.
I'm unable to say why the dateformat rise an exception. :o(
A snippet of my code :
package main;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
public class dateTestConv {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String dateOK1 = new String("21/01/2017");
convertDateStringEuroToDateObject(dateOK1);
String dateOK2= "21/01/2017";
convertDateStringEuroToDateObject(dateOK2);
//From file =KO
collectDateFromFile();
}
public static Date convertDateStringEuroToDateObject(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.FRANCE);
Date d = null;
try {
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Paris"));
d = dateFormat.parse(date);
} catch (ParseException ex) {
Logger.getLogger(dateTestConv.class.getName()).log(Level.SEVERE, null, ex);
}
return d;
}
public static void collectDateFromFile(){
String dirName=new String("dates.txt");
File file = new File(dirName);
try {
FileInputStream fstreami = new FileInputStream(dirName);
DataInputStream in = new DataInputStream(fstreami);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String dateFormatNormal = strLine;
Date d0= convertDateStringEuroToDateObject(dateFormatNormal);
}
in.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The file dates.txt contains just one line : 21/01/2017
When the method collectDateFromFile() is called , this exception is rised :
SEVERE: null
java.text.ParseException: Unparseable date: "21/01/2017"
at java.text.DateFormat.parse(DateFormat.java:366)
at main.dateTestConv.convertDateStringEuroToDateObject(dateTestConv.java:52)
at main.dateTestConv.collectDateFromFile(dateTestConv.java:75)
at main.dateTestConv.main(dateTestConv.java:42)
Thanks for your help.
Simply put, the string is not what you think it is. So you need to debug it by comparing the received with the expected value. For example, if there is an unexpected unicode codepoint hiding in there, you might detect it like this: