简体   繁体   English

在 Java 中获取带有允许的文件名字符的完整语言环境日期和小时字符串的好方法是什么?

[英]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.无论哪种方式,都可能有更好的方法来实现我的目标,如果有任何改进,我将不胜感激。

java.time java.time

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.您正在使用几年前被现代java.time类取代的糟糕的日期时间类。

Avoid localized formats避免本地化格式

You asked for text representing the date-time value in various localized formats.您要求以各种本地化格式表示日期时间值的文本。 That approach is unwise in a file name.这种方法在文件名中是不明智的。

  • Localized formats may well contain characters that would be problematic on various file systems.本地化格式很可能包含在各种文件系统上会出现问题的字符。 Your example MM/dd/yyyy format using slash characters might cause problems on some Unix/ POSIX -oriented file systems.您使用斜杠字符的示例MM/dd/yyyy格式可能会导致某些面向 Unix/ POSIX的文件系统出现问题。
  • Localized formats may be misinterpreted by humans who assume a different custom.采用不同习惯的人可能会误解本地化格式。
  • Localized formats may make difficult or impossible parsing that string back to a date-time value.本地化格式可能会使将该字符串解析回日期时间值变得困难或不可能。

Instead, I strongly recommend using only standard ISO 8601 formats.相反,我强烈建议仅使用标准ISO 8601格式。

“Basic” variant of ISO 8601 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.此类字符串按字母顺序按时间顺序排序。

UTC世界标准时间

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”。

Zoned moment分区时刻

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.就像使用两位数的年份一样。


Java 中所有日期时间类型的表,包括现代和传统


About java.time关于java.time

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.DateCalendarSimpleDateFormat

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.

相关问题 替换字符串中不允许的字符的最佳方法是什么? - What is the best way to replace not allowed characters in a string? 在 JAVA 中获取给定日期范围(DateX 和 DateY)之间的所有星期一和星期四日期将是一个很好的实现 - What would be a good implementation to get all Monday and Thursday dates Between a given date range (DateX and DateY) in JAVA 在 String Java 中用全名替换所有特殊字符的最佳方法是什么? - What is the best way to replace all special characters with their full names in a String Java? 在 JAVA 中从 GMT 时间长获取语言环境日期时间字符串 - Get locale Date Time String from GMT time long in JAVA 获取java.util.date小时的最快方法? - Fastest way to get hour of java.util.date? 使用小时调整而不是语言环境来打印DateTime的最简单方法是什么? - What is the easiest way to print a DateTime using an hour adjustment instead of a locale? 解析完整日期(日期和小时)字符串到目前为止会导致异常 - Parsing a full date (date and hour) string to date causes exception 在Java中拆分非定界字符串的好方法是什么? - What's a good way to split a non-delimited string in Java? 什么语言可以替代Java? - What languages would be a good replacement for Java? Java Build; 满足这些要求,什么是不错的选择? - Java Build; with these requirements, what would be a good choice?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM