7

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

chris
  • 73
  • 1
  • 1
  • 5
  • Almost all of the [Date](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html) class methods are deprecated in favor of [Calendar](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html) or [GregorianCalendar](http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html) in Java7. – adamdc78 Feb 16 '15 at 17:41
  • 1
    There is no standard date format for CSV files, so you need to find out (or define) what date format is supposed to be used for your particular case and use it. – Hot Licks Feb 16 '15 at 19:56
  • (The problem with `Date.toString` is that it will produce a string such as "Monday, Feb 16 2015" and the embedded comma will upset the CSV parsing.) – Hot Licks Feb 16 '15 at 19:59

2 Answers2

4

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.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
1

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.

Community
  • 1
  • 1
hhanesand
  • 990
  • 11
  • 28