如何重新格式化时间格式?

How to reformat time format?

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

所以12:42:41 am应该变成00:4202:13:39 pm 应显示为 14:13.

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

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));

使用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 回答 and OleV.V. answer 以获得更好的解释。

使用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.

试试这个:

   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
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();
}

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 classes 取代了可怕的 Date & Calendar & SimpleDateFormat classes.

LocalTime class 表示通用 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 );

output: 10:12


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

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

从哪里获得java.time classes?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.