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....
}
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.
String start_dt = '2011-01-01'; DateFormat formatter = new SimpleDateFormat("YYYY-MM-DD"); Date date = (Date)formatter. parse(start_dt);
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.
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(":", "")));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With