Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and write date and time into CSV file

Tags:

java

date

csv

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

like image 503
chris Avatar asked Feb 16 '15 17:02

chris


People also ask

Can you read and write to a CSV file at the same time?

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.

How do I convert a date to a CSV file?

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.


2 Answers

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.

like image 115
ᴇʟᴇvᴀтᴇ Avatar answered Sep 22 '22 12:09

ᴇʟᴇvᴀтᴇ


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.

like image 41
hhanesand Avatar answered Sep 22 '22 12:09

hhanesand