Solved

SimpleDateFormat does not recognize date in csv

Posted on 2012-03-10
10
470 Views
Last Modified: 2012-08-14
I read in a csv file with multiple columns with one date column in the beginning. When you open the file, the date looks like 5/16/1997. However, once the file is read, the date string becomes "1997-05-16".

When I call SimpleDateFormat.parse("1997-05-16"), it throws a ParseException.

any reason why the date format is altered when read, and why SimpleDateFormat can not recognize the date?
0
Comment
Question by:bhomass
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 2
10 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 37706240
> When you open the file, the date looks like 5/16/1997. However, once the file is read, the date string becomes "1997-05-16".

How can that be?

please, show your code
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37706242
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

java.util.Date dd = sdf.parse("1997-05-16",new ParsePosition(0));

should work
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37706245
This is tested and works without problems:

SimpleDateFormat sdf750 = new SimpleDateFormat("yyyy-MM-dd");

java.util.Date dd750 = sdf750.parse("1997-05-16",new ParsePosition(0));

        System.out.println(dd750);

Open in new window


Output:

Fri May 16 00:00:00 PDT 1997

Open in new window

1
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:bhomass
ID: 37706248
I need this code to work w/o knowing the exact format. So I don't want to specify new SimpleDateFormat("yyyy-MM-dd");

my code for reading the csv.

try {
                  File csvFile = new File(uploadDir + filename);
                  BufferedReader bufRdr = new BufferedReader(new FileReader(csvFile));
                  String line = null;
                  int row = 0;

                  // read each line of text file
                  while ((line = bufRdr.readLine()) != null) {
                        List<String> oneLine = new ArrayList<String>();
                        StringTokenizer st = new StringTokenizer(line, ",");
                        while (st.hasMoreTokens()) {
                              // get next token and store it in the array
                              oneLine.add(st.nextToken());
                        }
                        if (row==0){
                              headers = oneLine;
                        } else {
                              dataLines.add(oneLine);
                        }
                        row++;
                  }
                  bufRdr.close();
                  return buildRecords(headers, dataLines);
            } catch (Exception ex) {
                  ex.printStackTrace();
            }
0
 
LVL 47

Accepted Solution

by:
for_yan earned 200 total points
ID: 37706249
You cannot parse the date without knowing the foramt - you may go through a number of possible formats if you want, but without knowledge of any possible formats
you cannot parse out the date
- you need to enumerate at least some finite number of possibl formats
and then go through them one by one finding the one which works
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37706258
In this way you can test any number of formats,
but still you need to be sure that date will follow at least
one of the expected formats:

SimpleDateFormat sdf750 = new SimpleDateFormat("yyyy-MM-dd");
 SimpleDateFormat       sdf751 = new SimpleDateFormat("yyyy/MM/dd");

        sdf750.setLenient(false);
        String dateString = "1997/05/16";

java.util.Date dd750 = sdf750.parse(dateString,new ParsePosition(0));

         if(dd750 == null) {
             System.out.println(" trying again");
                dd750 = sdf751.parse(dateString,new ParsePosition(0));
         }

        System.out.println(dd750);

Open in new window


Output:
 trying again
Fri May 16 00:00:00 PDT 1997

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37706259
You actually should setLenient(false) on all SimpleDateFormat instances whoch you would use, so better add one more setLenient(false) like here:

SimpleDateFormat sdf750 = new SimpleDateFormat("yyyy-MM-dd");
 SimpleDateFormat       sdf751 = new SimpleDateFormat("yyyy/MM/dd");

        sdf750.setLenient(false);
        sdf751.setLenient(false);
        String dateString = "1997/05/16";

java.util.Date dd750 = sdf750.parse(dateString,new ParsePosition(0));

         if(dd750 == null) {
             System.out.println(" trying again");
                dd750 = sdf751.parse(dateString,new ParsePosition(0));
         }

        System.out.println(dd750);

Open in new window

0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 200 total points
ID: 37706263
> When you open the file, the date looks like 5/16/1997.
don't try to open csv file by double-clicking it, when it opens it in Excel

Open csv file in the Notepad - then you'll see it the way java will be reading it - not with Excel, where Exc el does a number of changes after reading the actual file
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37706270
Yes, I tested, and created the csv file with these dates, which I enetred with Notrpad:

abc,1,03-05-1997
def,3,11-03-2002


when I opened this csv file in Excel,
Excel showed dates with slashes

03/05/1997
11/3/2002


It is definitel the Excel which transfroms the way the date is shown.

So when you read .csv file with java you program will of couse read it as they sit in the csv
file
03-05-1997
Open your file with Notepad - and that's how your java program will see everything in the file.
Don't open in excel - it becomes misleading, as Excle makes transformation of its own
0
 

Author Comment

by:bhomass
ID: 37708481
This comment - "You cannot parse the date without knowing the foramt" was not true. it will parse some common date patterns successfully even if you never fed it any pattern, just not the unusual pattern "yyyy-MM-dd".

The case about the internal format differing from Excel display was true.

I ended out listing all possible date patterns I might run into, as suggested by one of the experts.
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question