【问题标题】:How to reformat time format?如何重新格式化时间格式?
【发布时间】:2019-02-27 04:35:04
【问题描述】:

我正在开发 android 项目,我从 API 收到格式为“10:12:57 am”(12 小时格式)的时间,我想以“10:12”格式显示它,就像这样( 24 小时制)。如何重新格式化那个时间?

所以12:42:41 am 应该变成00:42。并且02:13:39 pm 应该显示为14:13

【问题讨论】:

  • API返回的对象是String吗?如果 "10:12:57 am" 是一个字符串,那么您只需使用 substring(0,5) 从字符串中获取前五个字符。
  • 可能Duplicate
  • @HuzaifaIftikhar 但它是 12 小时制,我想在 24 小时内完成
  • 小时数小于10时API如何返回时间?是像“09:12:57 am”还是“9:12:57 am”?根据这一点,您可以轻松地将其自行转换为 24 小时格式。
  • 不是that linked Question 的副本。该问题涉及一个时刻,一个带有时间的日期和一个与 UTC 的偏移量。这个问题是关于一个单独的时间,没有日期,没有偏移,没有时区。

标签: java android datetime time time-format


【解决方案1】:

使用 java.time(现代方法)

String str = "10:12:57 pm";

DateTimeFormatter formatter_from = DateTimeFormatter.ofPattern( "hh:mm:ss a", Locale.US ); //Use pattern symbol "hh" for 12 hour clock
LocalTime localTime = LocalTime.parse(str.toUpperCase(), formatter_from );
DateTimeFormatter formatter_to = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ); // "HH" stands for 24 hour clock

System.out.println(localTime.format(formatter_to));

请参阅 BasilBourque 回答 below 和 OleV.V。回答here以获得更好的解释。

使用 SimpleDateFormat

String str = "10:12:57 pm";

    SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss a", Locale.US); 

    //Locale is optional. You might want to add it to avoid any cultural differences.

    SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm", Locale.US);

    try {
        Date d = formatter_from.parse(str);

        System.out.println(formatter_to.format(d));

    } catch (ParseException e) {           
        e.printStackTrace();
    }

如果您的输入是上午 10:12:57,那么输出将是 10:12。如果字符串是 10:12:57 pm,则输出将是 22:12。

【讨论】:

  • 错误 ==> 无法解析的日期:偏移 9 处的“10:12:57 am”
  • 访问this
  • 完全没有,而是编辑你的答案,使其对它的每一个提供都像我一样。谢谢
  • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。大多数 java.time 功能在 ThreeTen-Backport 项目中被反向移植到 Java 6 和 Java 7。在ThreeTenABP 项目中进一步适用于早期的Android。见How to use ThreeTenABP…
  • 此代码误用 date-with-time-of-day 类来保存仅 time-of-day 值。圆孔中的方钉。
【解决方案2】:

tl;博士

LocalTime                                                    // Represent a time-of-day, without a date and without a time zone.
.parse(                                                      // Parse an input string to be a `LocalTime` object.
    "10:12:57 am".toUpperCase() ,                            // The cultural norm in the United States expects the am/pm to be in all-uppercase. So we convert our input value to uppercase.
    DateTimeFormatter.ofPattern( "hh:mm:ss a" , Locale.US )  // Specify a formatting pattern to match the input. 
)                                                            // Returns a `LocalTime` object.
.format(                                                     // Generate text representing the value in this date-time object.
    DateTimeFormatter.ofPattern( "HH:mm" , Locale.US )       // Note that `HH` in uppercase means 24-hour clock, not 12-hour.
)                                                            // Returns a `String`.

10:12

java.time

现代方法使用 java.time 类,该类在几年前取代了可怕的 Date & Calendar & SimpleDateFormat 类。

LocalTime 类表示一般 24 小时制一天中的时间,没有日期和时区。

将您的字符串输入解析为LocalTime 对象。

String input = ( "10:12:57 am" );
DateTimeFormatter fInput = DateTimeFormatter.ofPattern( "HH:mm:ss a" , Locale.US );
LocalTime lt = LocalTime.parse( input.toUpperCase() , fInput );  // At least in the US locale, the am/pm is expected to be in all uppercase: AM/PM. So we call `toUppercase` to convert input accordingly.

lt.toString(): 10:12:57

生成一个String,其中包含您想要的小时-分钟格式的文本。请注意,大写的HH 表示 24 小时制。

DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US );
String output = lt.format( fOutput );

输出:10:12


关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

从哪里获得 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

【讨论】:

    【解决方案3】:

    试试这个:

       SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
       SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
       try {
             Date date = parseFormat.parse("10:12:57 pm");
             System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
           } 
       catch (Exception e) {
             e.printStackTrace();
           }  
    

    给予:

    10:12:57 pm = 22:12
    

    【讨论】:

      【解决方案4】:

      你可以使用这样的格式化程序:

      SimpleDateFormat formatterFrom = new SimpleDateFormat("hh:mm:ss aa");
      SimpleDateFormat formatterTo = new SimpleDateFormat("HH:mm");
      
      Date date = formatterFrom.parse("10:12:57 pm");
      System.out.println(formatterTo.format(date));
      

      【讨论】:

      • 我测试它并抛出解析异常!
      • 错误 ==> 无法解析的日期:偏移 9 处的“10:12:57 pm”
      • 好的,试试这个
      【解决方案5】:
      String str ="10:12:57 pm";
      
      SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss aa", Locale.US);
      SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm",Locale.US);
      
      try {
          Date d = formatter_from.parse(str);
      
          System.out.println(formatter_to.format(d));
      
      } catch (ParseException e) {           
          e.printStackTrace();
      }
      

      【讨论】:

      • 请不要教年轻人使用早已过时且臭名昭著的 SimpleDateFormat 类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API 和它的DateTimeFormatter 中做得更好。
      猜你喜欢
      • 1970-01-01
      • 2020-12-28
      • 2021-12-28
      • 1970-01-01
      • 2011-04-05
      • 2013-04-09
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      相关资源
      最近更新 更多