[英]What would be a good way to get a full locale date and hour string with allowed filename characters, in Java?
I want to build a string with the locale date and hour, concatenated, that must be human readable and compatible with the most common OS file allowed characters as well.我想构建一个带有区域设置日期和时间的字符串,连接起来,它必须是人类可读的并且与最常见的 OS 文件允许的字符兼容。 Something like:
就像是:
6-23-20_03-06-50
6-23-20_03-06-50
I am using this as an automated filename suggestion for the user.我将其用作用户的自动文件名建议。 To achieve this, I have written the following code:
为此,我编写了以下代码:
public class CustomDateProvider {
private static final String TWO_DIGIT_PATTERN = "%02d";
public static String getDashedDateAndHourFromDate(Date date) {
ZonedDateTime dateTime = date.toInstant().atZone(ZoneId.systemDefault());
int hour = dateTime.getHour();
int minute = dateTime.getMinute();
int second = dateTime.getSecond();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
String localeDate = dateFormat.format(date);
String dashedDate = localeDate.replace("/", "-");
return dashedDate
+ "_"
+ String.format(TWO_DIGIT_PATTERN, hour)
+ "-"
+ String.format(TWO_DIGIT_PATTERN, minute)
+ "-"
+ String.format(TWO_DIGIT_PATTERN, second);
}
}
Thus, I am assuming the date separator char will always be " / ", and I am not sure if this is always correct.因此,我假设日期分隔符 char 将始终为“ / ”,我不确定这是否始终正确。 Either way, there are probably better ways to achieve my goal, and I would appreciate any improvement.
无论哪种方式,都可能有更好的方法来实现我的目标,如果有任何改进,我将不胜感激。
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.您正在使用几年前被现代java.time类取代的糟糕的日期时间类。
You asked for text representing the date-time value in various localized formats.您要求以各种本地化格式表示日期时间值的文本。 That approach is unwise in a file name.
这种方法在文件名中是不明智的。
MM/dd/yyyy
format using slash characters might cause problems on some Unix/ POSIX -oriented file systems.MM/dd/yyyy
格式可能会导致某些面向 Unix/ POSIX的文件系统出现问题。 Instead, I strongly recommend using only standard ISO 8601 formats.相反,我强烈建议仅使用标准ISO 8601格式。
You asked for:您要求:
must be human readable and compatible
必须是人类可读和兼容的
I suggest sticking with the "basic" variant of ISO 8601 format that makes minimal use of delimiters.我建议坚持使用最少使用分隔符的ISO 8601格式的“基本”变体。 For compatibility with various filesystems you want to avoid slash, backslash, colon, and space characters.
为了与各种文件系统兼容,您希望避免使用斜杠、反斜杠、冒号和空格字符。
The ISO 8601 format is in order of significance: year, month, day, hour, minute, second, fractional second. ISO 8601 格式按重要性顺序排列:年、月、日、小时、分钟、秒、小数秒。 An uppercase
T
separates the date portion from the time-of-day portion.大写的
T
将日期部分与时间部分分开。 Such strings sort alphabetically as chronological.此类字符串按字母顺序按时间顺序排序。
I also suggest you stick with UTC (an offset of zero hours-minutes-seconds).我还建议您坚持使用UTC (零时分秒的偏移量)。 For this, use
Instant
(or OffsetDateTime
set to UTC).为此,请使用
Instant
(或OffsetDateTime
设置为 UTC)。
Instant instant = Instant.now() ; // Capture current moment as seen in UTC.
Truncate if you do not want fractional seconds or minutes.如果您不想要小数秒或分钟,请截断。
Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES ) ;
You would do string manipulation to remove the hyphens between the year-month-day and the colons between the hour-minute-second.您将进行字符串操作以删除年-月-日之间的连字符和小时-分-秒之间的冒号。
String output = instant.replace( "-" , "" ).replace( ":" , "" ) ;
For 2021-01-23T12:30:35Z that would be:对于 2021-01-23T12:30:35Z 这将是:
20210123T123035Z
20210123T123035Z
The trailing Z
means UTC, and is pronounced “Zulu”.后面的
Z
表示 UTC,发音为“Zulu”。
If you insist on using the date-time as seen in a particular time zone, use ZonedDateTime
.如果您坚持使用特定时区中的日期时间,请使用
ZonedDateTime
。
ZoneId z = ZoneId.systemDefault() ; // Or ZoneId.of( "Africa/Tunis" ) and such.
ZonedDateTime zdt = ZonedDateTime.now().truncatedTo( ChronoUnit.MINUTES ) ;
Specify a formatting pattern.指定格式模式。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" ) ;
String output = zdt.format( f ) ;
Example:例子:
20210123T123035
20210123T123035
I do not recommend omitting the zone or offset, but there you go if you insist.我不建议省略区域或偏移量,但如果你坚持的话,你会看到 go。
If you insist your example format of 6-23-20_03-06-50
, define a DateTimeFormatter
to match.如果您坚持使用
6-23-20_03-06-50
的示例格式,请定义一个DateTimeFormatter
来匹配。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M-d-uu'_'HH-mm-ss" ) ;
Allowing single-digit month or day is yet another thing I recommend against.允许一位数的月份或日期是我反对的另一件事。 As is the use of a two-digit year.
就像使用两位数的年份一样。
The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
, Calendar
, & SimpleDateFormat
.这些类取代了麻烦的旧日期时间类,例如
java.util.Date
、 Calendar
和SimpleDateFormat
。
To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程。 And search Stack Overflow for many examples and explanations.
并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .
规范是JSR 310 。
The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式的Joda-Time项目建议迁移到java.time类。
You may exchange java.time objects directly with your database.您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later.
使用符合JDBC 4.2或更高版本的JDBC 驱动程序。 No need for strings, no need for
java.sql.*
classes.不需要字符串,不需要
java.sql.*
类。 Hibernate 5 & JPA 2.2 support java.time . Hibernate 5 & JPA 2.2 支持java.time 。
Where to obtain the java.time classes?从哪里获得 java.time 课程?
Here is how you can get the locale Date_Time-以下是如何获取语言环境 Date_Time-
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTimeExample {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current Date and Time: "+currentDateTime);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("uuuu-MM-dd_hh-mm-ss");
System.out.println("Date Time in 12 Hour format - " + currentDateTime.format(pattern));
}
}
For more details please see this Get Locale Date_Time有关更多详细信息,请参阅获取区域设置 Date_Time
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.