Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why parsing a String into Date in Java is slow? Can we accelerate it?

I am reading a text file containing dates, and I want to parse the Strings representing the dates into Date objects in java. What I notice is the operation is slow. Why? is there any way to accelerate it? My file looks like:

2012-05-02 12:08:06:950, secondColumn, thirdColumn
2012-05-02 12:08:07:530, secondColumn, thirdColumn
2012-05-02 12:08:08:610, secondColumn, thirdColumn

I am reading the file line by line, then I am getting the date String from each line, then I am parsing it into a Date object using a SimpleDateFormat as follow:

DataInputStream in = new DataInputStream(myFileInputStream);
BufferedReader  br = new BufferedReader(new InputStreamReader(in));
String strLine;

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while ((strLine = br.readLine()) != null)
{
    ....Do things....
    Date myDateTime = (Date)formatter.parse(myDateString);
    ...Do things....
}
like image 574
Rami Avatar asked Aug 03 '12 14:08

Rami


People also ask

How to convert a String into Date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How to convert yyyy MM dd String to Date in Java?

String start_dt = '2011-01-01'; DateFormat formatter = new SimpleDateFormat("YYYY-MM-DD"); Date date = (Date)formatter. parse(start_dt);

How to convert String to Date using DateTimeFormatter?

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale. ENGLISH); String dateInString = "7-Jun-2013"; Date date = formatter. parse(dateInString); In the above example, we first need to construct a SimpleDateFormat object by passing the pattern describing the date and time format.


1 Answers

The converting of dates and timezone is expensive. If you can assume your date/times are similar to each other, you can convert the date and hours/minutes (or only dates if you use GMT) whenever minutes change and generate the seconds yourself.

This will call parse once per minute. Depending on your assumptions you could make it once per hours or once per day.

String pattern = "yyyy-MM-dd HH:mm";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
String lastTime = "";
long lastDate = 0;
while ((strLine = br.readLine()) != null) {
    String myDateString = strLine.split(", ")[0];
    if (!myDateString.startsWith(lastTime)) {
        lastTime = myDateString.substring(0, pattern.length());
        lastDate = formatter.parse(lastTime).getTime();
    }
    Date date = new Date(lastDate + Integer.parseInt(myDateString.substring(pattern.length() + 1).replace(":", "")));
}
like image 159
Peter Lawrey Avatar answered Sep 20 '22 12:09

Peter Lawrey