如何从Java 5中的文本文件中读取时间和日期?

时间:2011-07-20 20:53:01

标签: java parsing datetime file-io text-files

我正在尝试使用Java 5 SE从纯文本文件中读取数据。数据采用以下格式:

10:48 AM
07/21/2011

我研究过DateFormat和SimpleDateFormat,但我无法弄清楚将这些数据读入Date对象的最直接方式。

这是我到目前为止所拥有的:

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.");
        }
    }
}

我在这里走在正确的轨道上吗?最好的方法是什么?

4 个答案:

答案 0 :(得分:7)

首先将这两行连接成这样的字符串:String date =“07/21/2011 10:48 AM”

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

这应该有效,您可以参考SimpleDateFormat API了解更多选项。

答案 1 :(得分:2)

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

根据您的格式更改SimpleDateFormat参数。

答案 2 :(得分:1)

使用诸如Guava之类的库而不是编写自己的文件来读取样板代码,您可以使用以下内容:

 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));

(在上面的例子中省略了IOException和ParseException的处理。)

答案 3 :(得分:0)

试试这个,

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StringToDateDemo
{
   public static void main(String[] args) throws ParseException  
   {
      String strDate = "05/23/14 5:10 am";
      SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy h:mm a");
      Date dt = sdf.parse(strDate);
      System.out.println(dt);
   }
}

如需更多参考链接,

https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

http://www.flowerbrackets.com/java-convert-string-date/