2

I'm trying to read data from a plain text file using Java 5 SE. The data is in the following formats:

10:48 AM
07/21/2011

I've looked into DateFormat and SimpleDateFormat, but I can't figure out the most straight-forward way of reading this data into a Date object.

Here's what I have so far:

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

class Pim {

    File dataFile;
    BufferedReader br;
    String lineInput;
    Date inputTime;
    Date inputDate;

    public Pim() {

        dataFile = new File("C:\\Data.txt");

        try {

            br = new BufferedReader(new FileReader(dataFile));

            lineInput = br.readLine();
            inputTime = new Date(lineInput);

            lineInput = br.readLine();
            inputDate = new Date(lineInput);            

            br.close();

        } catch (IOException ioe) {

            System.out.println("\n An error with the Data.txt file occured.");
        }
    }
}

Am I on the right track here? What's the best way to do this?

Jonik
  • 80,077
  • 70
  • 264
  • 372
dvanaria
  • 6,593
  • 22
  • 62
  • 82

3 Answers3

8

First concat the two lines to have something like this: String date = "07/21/2011 10:48 AM"

DateFormat formatter = new SimpleDateFormat("MM/dd/yy h:mm a");
Date date = (Date)formatter.parse(date);

This should work, you can refer to SimpleDateFormat API for more options.

Marsellus Wallace
  • 17,991
  • 25
  • 90
  • 154
  • This makes sense - and it's easier to combine the date & time this way than starting with two Date instances. +1 – Jonik Jul 20 '11 at 21:18
2

http://www.kodejava.org/examples/19.html

Change the SimpleDateFormat param as per your format.

Kumar Bibek
  • 9,016
  • 2
  • 39
  • 68
1

Using a library such as Guava instead of writing your own file reading boilerplate code, you could get away with something like:

 List<String> lines = 
     Files.readLines(new File("C:\\Data.txt"), Charset.forName("UTF-8"));

 DateFormat timeFormat = new SimpleDateFormat("hh:mm a");
 Date time = timeFormat.parse(lines.get(0));

 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
 Date date = dateFormat.parse(lines.get(1));

(Handling of IOException and ParseException omitted in above example.)

Jonik
  • 80,077
  • 70
  • 264
  • 372