【发布时间】:2014-12-10 11:05:42
【问题描述】:
由于我们可以在 java 中将当前时间作为文件名,我们也可以对文件夹做同样的事情吗? 我们可以将文件夹的名称作为当前时间戳吗? 请帮忙。谢谢。
【问题讨论】:
由于我们可以在 java 中将当前时间作为文件名,我们也可以对文件夹做同样的事情吗? 我们可以将文件夹的名称作为当前时间戳吗? 请帮忙。谢谢。
【问题讨论】:
是这样的。
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh mm ss");
String time = dateFormat.format(now);
File dir = new File(time);
dir.mkdir();
【讨论】:
类似于James Fox 的the answer,我建议使用 Joda-Time 2.6(或 java.time)在 Java 中进行所有日期时间工作。
我建议使用标准的ISO 8601 格式2014-12-10T17:05:33Z。字母排序恰好也是按时间顺序排序的。另一个好处是可以在几乎所有文化中进行明确的阅读。
除了替换 COLON 以与 Mac 的 HFS+ file system 兼容。我已经看到它们被 HYPHEN - 或 FULL STOP .(句号)取代。
结果值 2014-12-10T17-05-33Z 与我所知道的所有常见操作系统兼容,除了 MS-DOS(8.3 naming 的字符太多)。
不要替换为 SOLIDUS(斜杠)或 REVERSE SOLIDUS(反斜杠),以便与 Unix 风格的操作系统和 Microsoft Windows 操作系统兼容。
有关更多信息,请阅读 Apple 的这篇文章,OS X: Cross-platform filename best practices and conventions。
最好指定所需的时区,而不是隐式依赖 JVM 当前的默认时区。
如果跨计算机混合和匹配文件,您可能希望坚持使用UTC 作为时区。
DateTime now = DateTime.now( DateTimeZone.UTC );
String output = now.toString().replace( ":" , "-" ); // Replace colons for compatibility with the Mac HFS+ file system.
File f = new File( output );
f.mkdir();
输出:
output : 2014-12-10T22-35-28.460Z
如果要使用用户的JVM当前默认时区。
DateTime now = DateTime.now( DateTimeZone.getDefault() );
…
output : 2014-12-10T14-49-00.752-08-00
也许您想要一个特定的时区,例如公司总部的时区。
DateTime now = DateTime.now( DateTimeZone.forID( "America/Montreal" ) );
您可能希望删除小数秒以使用整秒或整分钟。 Joda-Time 有内置的格式化程序,dateHourMinuteSecond() 或 dateHourMinute()。这些格式省略了Z 或时区偏移量。为了清楚起见,我建议附加;注意下面的+"Z"。
DateTime now = DateTime.now( DateTimeZone.UTC );
DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecond(); // Or dateHourMinute();
String output = formatter.print( now ).replace( ":" , "-" )+"Z"; // Replace colons for compatibility with the Mac HFS+ file system.
File f = new File( output );
f.mkdir();
运行时:
output : 2014-12-10T23-07-11Z
另一种选择是不使用标点符号,例如20141211T214342Z。
此类格式甚至被 ISO 8601 视为标准,使用最少数量的分隔符的格式被正式称为“基本”。
DateTime now = DateTime.now( DateTimeZone.UTC );
DateTimeFormatter formatter = ISODateTimeFormat.basicDateTimeNoMillis();
String output = formatter.print( now );
File f = new File( output );
f.mkdir();
【讨论】:
如果您使用的是 JodaTime,那么可以这样做:
DateTime date = DateTime.now();
File f = new File("C:\\tmp\\"+ date.getMillis());
f.mkdir();
您会得到一个名为 1418210024492 的文件夹(基于我运行它的时间)。
如果你想要时间戳作为日期,那么你可以这样做:
File f = new File("C:\\tmp\\" + date);
日期也可以按您的意愿设置格式,如下所示:
String dateTime = new DateTime().toString("dd-MM-yy HH:mm:ss");
File f = new File("C:\\tmp\\" + dateTime);
f.mkdir();
我更喜欢使用JodaTime,因为它更容易实现日期和时间。
【讨论】:
Date date =new Date();
String s=""+date.getTime();
File file = new File("rootpath"+s);
file.mkdir();
【讨论】: