java 将日期和时间读取和写入 CSV 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28547162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read and write date and time into CSV file
提问by chris
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. So how do I write to the CSV file in a format that can be read afterwards?
它给了我一个非常优雅的字符串来描述日期和时间,它似乎无法存储到 CSV 文件中并在以后读取。那么如何以以后可以读取的格式写入 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
感谢任何帮助。谢谢
采纳答案by ???v?т?
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.
根据您的用例,您可能还会发现明确设置时区(例如设置为 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.
如果您需要有关读取/写入文件或异常处理的帮助,我建议您提出单独的问题。
回答by hhanesand
You could try storing the data as a Unix Timestamp(simply a long number).
您可以尝试将数据存储为Unix 时间戳(只是一个长数字)。
Read this questionto figure out how to get the unix time stamp and thisto figure out how to convert it back to a Date object.