如何将"hh:mm AM/PM"字符串转换为格式化时间?



我的字符串输入为" 03:00 pm"或" 09:00 am",我想将其转换为格式化的时间甚至是整数。这样我就可以按时间顺序进行比较。有人可以帮助我吗?

预先感谢您。

尝试此

import java.text.SimpleDateFormat;  
    import java.util.Date;  
    public class StringToDateExample1 {  
    public static void main(String[] args)throws Exception {  
        String sDate1="03:00 PM";  
        Date date1=new SimpleDateFormat("HH:mm").parse(sDate1);  
    }  
   }  

tl; dr

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
    String input = "03:00 PM";
    LocalTime time = LocalTime.parse(input, inputFormatter);
    System.out.println(time);

此打印

15:00

编辑:由于您的时间格式为英语,因此使用此格式化器可能被认为更清洁:

    DateTimeFormatter inputFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
                    .withLocale(Locale.ENGLISH);

它几乎匹配。后者的格式格式在10个数小时之前仅使用一位数字,例如5:12 AM,但在解析时也接受两个数字,因此可以使用。

java.Time

我建议您使用java.time中的LocalTime代表一天中的时间,这正是它的目的。因此,它为您提供了良好的建模和自我记录的代码。

其他答案是正确的,但很差。虽然您应该将库类用于任务,但至少出于三个原因,不应使用SimpleDateFormatDate。(1(它们长期过时且设计较差;(2(DateFormatSimpleDateFormat尤其是麻烦的;(3(Date不代表一天的时间。

比较时间

    LocalTime anotherTime = LocalTime.parse("09:00 AM", inputFormatter);
    if (anotherTime.isBefore(time)) {
        System.out.println("" + anotherTime + " comes before " + time);
    } else {
        System.out.println("" + time + " comes before " + anotherTime);
    }

此打印

09:00 comes before 15:00

再次使用LocalTime进行比较,比使用格式的字符串更清晰。可能更好,LocalTime实现Comparable,因此您可以使用Collections.sort()和其他依赖对象自然顺序的功能。

如果您确实想要一个格式的字符串,则第一个选项是LocalTime.toString()

    String formattedTime = time.toString();
    System.out.println(formattedTime);

这与我们上面的15:00打印出相同的输出。如果您想要其他格式,请定义第二个DateTimeFormatter并在LocalTime.format()中使用它。

问题:我可以在Android上使用Java.Time吗?

是的,您可以在Android上使用java.time。它至少需要Java 6

  • 在Java 8及以后以及在较新的Android设备上现代API内置。
  • 在Java 6和7中获得了新班的式向后港口(JSR 310的Threeten;请参阅底部的链接(。
  • (。
  • 在较旧的Android上使用Threeten Backport的Android Edition。它叫做三分之一。并确保您从org.threeten.bp导入带有子包的日期和时间类。

链接

  • Oracle教程:解释如何使用java.time的日期时间。
  • Java规范请求(JSR(310,首先描述了java.time
  • Threeten Backport Project,java.time的Backport到Java 6和7(JSR-310的Threeten(。
  • Threetenabp,Threeten Backport的Android Edition
  • 问题:如何在Android项目中使用Threetenabp,并具有非常详尽的解释。

这可能不是最好的解决方案。但是您可以做的是将输入时间转换为秒,然后比较整数值。

以下功能可以帮助您想到获得几秒钟的想法。(只是伪代码。不是经过测试的代码(

public int getSeconds(String timeValue){
String[] splitByColon = timeValue.split(":"); 
int hoursValue = Integer.parseInt(splitByColon[0])); 
String[] splitForMins = splitByColon[1].split(" "); 
if(splitForMins[1].equals("PM"))
{
hoursValue = hoursValue + 12; 
}
int minutesValue = Integer.parseInt(splitForMins[0]); 
return 3600*hoursValue + 60*minutesValue; 
}

您可以使用dateformat。如果您确定所有都是英语,请使用Locale.ENGLISH

static Date convertTimeString(String timeString) {
    try {
        return DateFormat.getTimeInstance(DateFormat.SHORT, Locale.ENGLISH)
                .parse(timeString);
    } catch(ParseException e) {
        Log.e("CONVERTDATE", "String "" + timeString + "" couldn't be parsed");
        return null;
    }
}

做到这一点的最佳方法。

  1. 首先从(编辑文本或其他(获取字符串。
  2. 将字符串分为2部分时间编号'am'或'pm'
  3. 检查2位数是AM还是PM SO
  4. 检查字符串是AM还是PM,因此如果字符串是PM添加数字时间带有 12 您将获得24小时格式的时间
SimpleDateFormat myFormat = new SimpleDateFormat("hh:mm a");
String time="09:00 AM";  
    try {
        Date date=myFormat.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

在日期变量上,您将有时间

您可以尝试以下代码:

String strTime = "03:00 pm";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm aa");
Date date = dateFormat.parse(strTime);
long time = date.getTime();
import java.util.*;
import java.text.*;
public class DateDemo {
   public static void main(String args[]) {
      String time1="10:00 AM",time2="11:00 PM";
      DateFormat dfrmt = new SimpleDateFormat ("hh:mm a");
      Date Dtime1 =new Date();
      Date Dtime2 =new Date();
      try{
         Dtime1 = dfrmt.parse(time1);
         Dtime2 = dfrmt.parse(time2);
      }catch(Exception e){
      }
      if(Dtime1.compareTo(Dtime2)>0){
          //DTime1 comes after Dtime2
          System.out.println(dfrmt.format(Dtime1) + " > " + dfrmt.format(Dtime2));
      }else if(Dtime1.compareTo(Dtime2)<0){
          //Dtime1 Comes Before Dtime2
           System.out.println(dfrmt.format(Dtime1) + " < " + dfrmt.format(Dtime2));
      }
      else{
          //Equal   
          System.out.println(dfrmt.format(Dtime1) + " == " + dfrmt.format(Dtime2));
      }
 }
}

尝试比较两个日期;创建DateTime对象并使用comapreTo()功能

最新更新