如何将日期格式:2020-09-28T11:47:37.217转换为仅11:47?

时间:2020-10-06 14:14:58

标签: java android android-studio

我通过api调用收到以下日期/时间格式:

"AcceptedDate": "2020-09-28T11:47:37.217",
"Pickup1ArrivedDate": "2020-10-06T17:28:12.6",
"Pickup1LoadedDate": "2020-10-06T17:57:54.84",
"Pickup1DepartedDate": "2020-10-06T18:18:59.927"

在Java / android studio中保存响应后,是否仍然以“ 11:47”格式显示时间。 任何帮助表示赞赏。谢谢:-)

5 个答案:

答案 0 :(得分:1)

您可以使用substring()创建用于执行此操作的方法:

 public String stripRedundantDate(String date){
     return date.substring(11, 16);
 }

以下程序:

public class Main{

     public static void main(String []args){
        String time = "2020-09-28T11:47:37.217";
        System.out.println(stripRedundantDate(time));
     }
     public static String stripRedundantDate(String date){
         return date.substring(11, 16);
     }
}

产生结果:

11:47

如果您的日期不是固定长度

使用以下内容:

 public static String stripRedundantDate(String date){
     return date.substring(date.indexOf(':')-2, date.indexOf(':')+3);
 }

答案 1 :(得分:0)

我会将其转换为日期对象,然后以这种方式使用

LocalDate date = LocalDate.parse(apiResult.get("AcceptedDate"));

然后,我将其格式化为您想要的样子:

SimpleDateFormat format = new SimpleDateFormat("HH:mm");

String dateString = format.format( date  ); // this string will be the time you are looking for

答案 2 :(得分:0)

科特林

fun formatDate(date: String): String {
        val input = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH)
        val output = SimpleDateFormat("12:08 PM", Locale.ENGLISH)
        return output.format(input.parse(date)!!)
    }

答案 3 :(得分:0)

只需在字母T之后输入接下来的5个字符

SELECT 
    ot.[CoSerNum] AS CoSerNum, 
    (SELECT MAX(ot.[CoSerNum]) FROM OutTest ot1 WHERE ot1.[CoSerNum] < ot.[CoSerNum]) AS lagCoSerNum  
FROM OutTest ot
WHERE ot.SO = [Enter SO];

答案 4 :(得分:0)

java.time,通过半途而废或通过ThreeTenABP

我建议您考虑使用Java.time(现代的Java日期和时间API)进行日期和时间工作。

    String acceptedDate = "2020-09-28T11:47:37.217";
    LocalDateTime dateTime = LocalDateTime.parse(acceptedDate);
    String timeString = dateTime.toLocalTime()
            .truncatedTo(ChronoUnit.MINUTES)
            .toString();
    System.out.println(timeString);

输出为:

11:47

问题:java.time是否不需要Android API级别26?

java.time在较新和较旧的Android设备上均可正常运行。它只需要至少 Java 6

  • 在Java 8和更高版本以及更新的Android设备(API级别26以上)中,内置了现代API。
  • 在非Android Java 6和7中,获得ThreeTen Backport,这是现代类的backport(JSR 310的ThreeTen;请参见底部的链接)。
  • 在较旧的Android上,请使用废除旧书或Android版本的ThreeTen Backport。称为ThreeTenABP。在后一种情况下,请确保使用子包从org.threeten.bp导入日期和时间类。

链接