Read and write date and time into CSV file

csv, date, java

Solution

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.

Problem

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

Original source

Related problems