由于我们可以在java中将当前时间作为文件名,我们也可以对文件夹执行相同的操作吗?我们可以将文件夹的名称作为当前时间戳吗?请帮忙.谢谢.
是这样的.
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh mm ss");
String time = dateFormat.format(now);
File dir = new File(time);
dir.mkdir();
Run Code Online (Sandbox Code Playgroud)
类似的答案由詹姆斯·福克斯,我建议使用乔达时间2.6(或java.time)在Java中所有的日期时间的工作。
我建议使用标准ISO 8601格式2014-12-10T17:05:33Z。字母排序碰巧也按时间顺序排序。另一个好处是几乎所有文化都可以进行清晰的阅读。
除了替换COLON以便与Mac的HFS +文件系统兼容之外。我已经看到它们被连字符-或.句号(句号)所取代。
结果值2014-12-10T17-05-33Z与除MS-DOS之外我所知道的每个常见OS兼容(8.3命名的字符太多)。
为了与Unix风格的操作系统和Microsoft Windows操作系统兼容,请不要用SOLIDUS(斜杠)或REVERSE SOLIDUS(反斜杠)代替。
有关更多信息,请阅读Apple OS X的这篇文章:跨平台文件名最佳实践和约定。
最好指定所需的时区,而不是隐式依赖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();
Run Code Online (Sandbox Code Playgroud)
输出:
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();
Run Code Online (Sandbox Code Playgroud)
如果要使用用户的JVM的当前默认时区。
DateTime now = DateTime.now( DateTimeZone.getDefault() );
…
Run Code Online (Sandbox Code Playgroud)
output : 2014-12-10T22-35-28.460Z
Run Code Online (Sandbox Code Playgroud)
也许您想要一个特定的时区,例如公司总部所在的时区。
DateTime now = DateTime.now( DateTimeZone.forID( "America/Montreal" ) );
Run Code Online (Sandbox Code Playgroud)
您可能希望将小数秒减少一秒钟或一整分钟。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();
Run Code Online (Sandbox Code Playgroud)
运行时:
DateTime now = DateTime.now( DateTimeZone.getDefault() );
…
Run Code Online (Sandbox Code Playgroud)
另一种选择是不使用标点符号,例如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();
Run Code Online (Sandbox Code Playgroud)