I need to be able to store current date (year, month, day) and time (Hour, min, sec) into a CSV file, and read them afterwards.
For creating Date I've tried to use
Date date = new Date();
to construct the current date, but when I
date.toString();
it gives me a very elegant string describing the date and time, which doesn't seem able to store into the CSV file and be read later on. So how do I write to the CSV file in a format that can be read afterwards?
Additionally, reading the CSV file, I've found suggestions like
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date d = df.parse("17/02/2015 01:18:15");
Is this possible, based on the format of the previous output? And what exceptions do I have to catch with this use?
Appreciate any help. Thank you
You can read and simultaneously write to a second file, then atomically move the second to overwrite the first - which is how these things are usually done.
The appropriate formatting for dates should be "dd/mm/yyyy". By default, Microsoft Excel changes the number of digits in the year from four down to two. You need to modify the formatting so that all four digits are included when saving your file.
To write a date with a date format:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(df.format(date));
To parse a date, you use the same format:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = df.parse("17/02/2015 01:18:15");
Depending on your use-case, you might also find it worthwhile to set the timezone explicitly (e.g. to UTC) so that you get the same results regardless of the local machine's timezone / daylight saving time etc.
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Alternatively you could use the underlying long
(millis since the epoch) that a Date is built on top of...
To write:
Date date = new Date();
System.out.println(date.getTime());
To read:
long dateValue = // As read from the file
Date date = new Date(dateValue);
Personally, I'd use a DateFormat
, even though it's more verbose and more work, as it will make the file contents human-readable.
If you want help with reading/writing files or exception handling, I suggest you ask separate questions.
You could try storing the data as a Unix Timestamp (simply a long number).
Read this question to figure out how to get the unix time stamp and this to figure out how to convert it back to a Date object.
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