Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read Time and Date from Text File in Java 5?

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?

like image 411
dvanaria Avatar asked Dec 21 '25 23:12

dvanaria


1 Answers

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.

like image 70
Marsellus Wallace Avatar answered Dec 24 '25 19:12

Marsellus Wallace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!