Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

java - Parse a date from a text file and convert the month to a number

I have a text file display the following:

      Date    Opening    Closing
 6-Mar-2006   11022.47   10958.59
 9-Jun-2006   11005.66   10972.28
 7-Dec-2006   10957.31   10980.69
28-Feb-2006   11096.75   10993.41
 8-Mar-2006   10977.08   11005.74

How can I read in this file and convert all the months in String to month in int display. "Mar" to 3, "Jun" to 6. etc

My code so far:

Scanner in= new Scanner(System.in);
        int N=in.nextInt();
        in.close();

        Scanner input=new Scanner(new File("file.txt"));
        while (input.hasNextLine()){
            String line=input.nextLine();
            String[] fields=line.split(" ");
            String date=fields[0];
            String[] datefields=date.split("-");
            String month=datefields[1];
*******************************************************
This is where I want to do the conversion.
*******************************************************

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a very simple example to process your file and split the string line and obtain the date object.

public class FileReaderExample
{
  public static void main(String[] args)
  {
    File file = new File("d:\text.txt");
    try
    {
      BufferedReader br = new BufferedReader(new FileReader(file));
      String line;
      int lineNo = 1;
      while ((line = br.readLine()) != null)
      {
        // ignore the first line of       Date    Opening    Closing
        if (lineNo != 1)
        {
          String[] itemsOnLine = line.trim().split("\s+");
          System.out.println("Your date is : " + itemsOnLine[0]);
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
          Date yourDate = simpleDateFormat.parse( itemsOnLine[0]);
          System.out.println(yourDate);
          Calendar calendar= Calendar.getInstance();
          calendar.setTime(yourDate);
          // Account for month starting at 0
          int month = calendar.get(Calendar.MONTH) +1 ;
          System.out.println("The month of the date is " + month);
        }
        lineNo++;
      }
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    catch (ParseException e)
    {
      e.printStackTrace();
    }
  }
}

EDIT: Added your month requirement


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...