简体   繁体   English

读取和写入CSV文件的日期和时间

[英]Read and write date and time into CSV file

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. 我需要能够将当前日期(年,月,日)和时间(小时,分钟,秒)存储到CSV文件中,然后再读取它们。

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. 它给了我一个非常优雅的字符串来描述日期和时间,它似乎无法存储到CSV文件中,以后可以阅读。 So how do I write to the CSV file in a format that can be read afterwards? 那么如何以可以在以后阅读的格式写入CSV文件?

Additionally, reading the CSV file, I've found suggestions like 另外,阅读CSV文件,我发现了类似的建议

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 谢谢

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 (eg to UTC) so that you get the same results regardless of the local machine's timezone / daylight saving time etc. 根据您的使用情况,您可能还会发现明确设置时区(例如UTC)是值得的,这样无论本地机器的时区/夏令时等如何,您都可以获得相同的结果。

df.setTimeZone(TimeZone.getTimeZone("UTC"));

Alternatively you could use the underlying long (millis since the epoch) that a Date is built on top of... 或者,您可以使用基础long (自纪元以来的毫秒),在...之上构建日期...

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. 就个人而言,我会使用DateFormat ,即使它更冗长,也更有效,因为它会使文件内容变得人性化。

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). 您可以尝试将数据存储为Unix时间戳 (只是一个长数字)。

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. 阅读这个问题弄清楚如何获得UNIX时间戳和这个弄清楚如何将其转换回一个Date对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM