1

I am trying to process the data from a weather station. I simply want to process and print (for now) the minimum and maximum temperatures each day starting from 2000/01/01 until today 2019/12/12. The weather station gives me the date in an integer yyyymmdd like 20191212 or 20030317. I store this, alongside the minimum and maximum temperatures in an integer array, of about 21000 rows long... I want the date to be displayed in yyyy/mm/dd, like 2019/12/12 or 2003/03/17. How exactly do I go about doing this?

This is my code

import java.io.*;

public class Main {
    public static void main(String args[]) {
        int rowAmount = 7152;   //the amount of rows in the document
        int[] temperatures = new int[rowAmount*3];  //makes an array 3 times the size of rowAmount, to fit date, min temp and max temp.
        try {   
            BufferedReader br = new BufferedReader(new FileReader("D:\\20002019minmaxtempbilt.txt")); // Makes the filereader

            String fileRead = br.readLine(); // reads first like
            int counter = 0;    //sets a counter
            while (fileRead != null) { // loops until the file ends.
                String[] tokenize = fileRead.split(","); //splits the line in 3 segements, date, min temp and max temp. And stores them in following variables
                int tempDate = Integer.parseInt(tokenize[0]);
                int tempMin = Integer.parseInt(tokenize[1]);
                int tempMax = Integer.parseInt(tokenize[2]);
                //adds the values to the array
                temperatures[counter] = tempDate;
                counter++;
                temperatures[counter] = tempMin;
                counter++;
                temperatures[counter] = tempMax;
            }
            // close file stream
            br.close();
        }
        catch (FileNotFoundException fnfe)
        {
            System.out.println("file not found");
        }

        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }

        // Displays the entire array, formatted by date neatly, hopefully.

        for(int i = 0; i<rowAmount; i =+ 3) {
            int tempDate = temperatures[i];
            int tempMin = temperatures[i+1];
            int tempMax = temperatures[i+2];
            drawLine(tempDate, tempMin, tempMax);
        }


    }

    public static void drawLine(int tempDate, int tempMin, int tempMax) {
        /*This is where I get stuck. I need to convert tempDate from an int yyyymmdd to either
          3 separate integers representing year, month and day; or I need to convert it to a 
          string that can be printed out yyyy/mm/dd.*/

        System.out.printf("");

    }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • For converting your integer to a `LocalDate` i posted [a new answer to one of the linked original questions here](https://stackoverflow.com/a/59316435/5772882). How to format it is described in many places, for example [How to format LocalDate to yyyyMMDD (without JodaTime)](https://stackoverflow.com/questions/45598094/how-to-format-localdate-to-yyyymmdd-without-jodatime). – Ole V.V. Dec 13 '19 at 05:10
  • I recommend that rather than storing your numbers in adjacent cells of an array, you design a class with a `LocalDate` field and two fields for min and max temperaturs. Then store instances of this class into an array (or list). – Ole V.V. Dec 13 '19 at 05:15

4 Answers4

2

Another way: if the integer value representing the date is stored in an int called date (example value: 20191212), then

  int day = date % 100;
  int month = (date/ 100) % 100;
  int year = date / 10000;

then you can use a Formatter to format the string output that you want.

FredK
  • 4,094
  • 1
  • 9
  • 11
1

A problem is that an integer of 20191212 really doesn't represent a date.

I would recommend NOT transforming tempDate into an integer and leaving it as a string.

Edit

Here is an example that uses the Java 8 time package classes: LocalDate, DateTimeFormatter, and DateTimeFormatterBuilder:

package stackoverflow;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

public class ParseStringDate {

    public static void main(String... args) {

        String dateString = "20191231";

        DateTimeFormatter dateTimeFormatterParser = DateTimeFormatter.ofPattern("yyyyMMdd");

        LocalDate localDate = LocalDate.parse(dateString, dateTimeFormatterParser);

        System.out.println(localDate);

        DateTimeFormatter dateTimeFormatterPrinter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        System.out.println(localDate.format(dateTimeFormatterPrinter));

        dateTimeFormatterPrinter = new DateTimeFormatterBuilder()
                .appendPattern("yyyy")
                .appendLiteral("/")
                .appendPattern("MM")
                .appendLiteral("/")
                .appendPattern("dd").toFormatter();

        System.out.println(localDate.format(dateTimeFormatterPrinter));
    }
}

Here is an example that uses SimpleDateFormat:

package stackoverflow;

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

public class DateFormattingFromString {

    public static void main(String... args) throws Exception {

        String tempDate = "20191212";

        SimpleDateFormat sdf1 = new SimpleDateFormat("YYYYmmdd");

        Date date = sdf1.parse(tempDate);

        // Now format the above date as needed...
        SimpleDateFormat sdf2 = new SimpleDateFormat("YYYY/mm/dd");

        System.out.println(sdf2.format(date));
    }
}

As pointed out in the comments, SimpleDateFormat and the Date classes are not super great to work with. They are mutable and therefore not thread safe. The new java.time package classes are immutable and therefore thread safe. The new classes are also easier to do date math with and comparisons.

hooknc
  • 4,854
  • 5
  • 31
  • 60
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Dec 13 '19 at 05:22
1

Since your date is a String to start with I see no reason to convert it to an Integer first. Using the more current java.time package you can use one formatter to convert from a String to LocalDate and then another to convert back to a String with the right format,

DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate date = LocalDate.parse(tokenize[0], inFormatter);

DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String outStr = outFormatter.format(date);

Since DateTimeFormatter is costly to initialise I would recommend you create both of them before the loop you have for reading the file.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • There are more than one good point in this answer. Rather than using `Integer.parseInt(tokenize[0])` for converting your date from a string to a number, it’s better to parse it into a `LocalDate` from the outset. And yes, `LocalDate` from java.time is the good and correct class to use for dates. – Ole V.V. Dec 13 '19 at 05:19
  • If you need to convert from a `LocalDate` to an x or y coordinate in a plot/chart, I believe that `date.toEpochDay()` will give you a number that you can work with. – Ole V.V. Dec 13 '19 at 05:27
0

I'd recommend using a DateFormat object, taking advantage of the parse(String) and format(Date) methods.

  • I certainly recommend against it. `DateFormat` is a notorious troublemaker and long outdated. Instead use `DateTimeFormatter` along with `LocalDate`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 13 '19 at 05:22