繁体   English   中英

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

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

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

10:48 AM
07/21/2011

我研究了 DateFormat 和 SimpleDateFormat,但我无法找出将这些数据读入 Date object 的最直接方法。

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

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

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

首先将这两行连接成这样: 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了解更多选项。

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

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

使用诸如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 的处理。)

尝试这个,

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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM