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

时间:2018-02-10 06:06:49

标签: java android android-studio datetime

我的字符串输入为“03:00 PM”或“09:00 AM”,我想将其转换为格式化时间甚至是整数。这样我就可以按时间顺序对它们进行比较。 任何人都可以帮助我吗?

提前谢谢。

8 个答案:

答案 0 :(得分:2)

试试这个

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

    }  
   }  

答案 1 :(得分:1)

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

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

其他答案都是正确但很差。虽然您应该为任务使用库类,但至少有三个原因不应使用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中获取ThreeTen Backport,新类的后端端口(适用于JSR 310的ThreeTen;请参阅底部的链接)。
  • 在较旧的Android上使用Android版的ThreeTen Backport。它被称为ThreeTenABP。并确保使用子包从org.threeten.bp导入日期和时间类。

链接

答案 2 :(得分:0)

您可以使用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;
    }
}

答案 3 :(得分:0)

最好的方法。

  1. 首先从(编辑文本或随意)中获取字符串。
  2. 将字符串拆分为2部分第1 时间数字'AM'或'PM'
  3. 检查2位数是AM还是PM
  4. 检查字符串是AM还是PM,如果字符串是PM,则添加 数字时间 12 您将获得24小时格式的时间

答案 4 :(得分:0)

SimpleDateFormat myFormat = new SimpleDateFormat("hh:mm a");
String time="09:00 AM";  
    try {

        Date date=myFormat.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

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

答案 5 :(得分:0)

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

以下功能可以帮助您了解秒数。 (只是一个伪代码。不是经过测试的代码)

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; 

}

答案 6 :(得分:0)

您可以尝试以下代码:

String strTime = "03:00 pm";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm aa");
Date date = dateFormat.parse(strTime);
long time = date.getTime();

答案 7 :(得分:0)

[{"id":"a600589b.f2b9f8","type":"ui_template","z":"54549b95.190a94","group":"ed0a0688.55eb78","name":"","order":0,"width":0,"height":0,"format":"<div id=\"demo\"></div>\n\n<script>\n// Set the date we're counting down to\n//var countDownDate = new Date({{msg.payload}}).getTime();\nvar indate = msg.payload;\nvar countDownDate = new Date(indate).getTime();\n\n// Update the count down every 1 second\nvar x = setInterval(function() {\n\n    // Get todays date and time\n    var now = new Date().getTime();\n    \n    // Find the distance between now an the count down date\n    var distance = countDownDate - now;\n    \n    // Time calculations for days, hours, minutes and seconds\n    var days = Math.floor(distance / (1000 * 60 * 60 * 24));\n    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));\n    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));\n    var seconds = Math.floor((distance % (1000 * 60)) / 1000);\n    \n    // Output the result in an element with id=\"demo\"\n    document.getElementById(\"demo\").innerHTML = days + \"d \" + hours + \"h \"\n    + minutes + \"m \" + seconds + \"s \";\n    \n    // If the count down is over, write some text \n    if (distance < 0) {\n        clearInterval(x);\n        document.getElementById(\"demo\").innerHTML = \"EXPIRED\";\n    }\n}, 1000);\n</script>\n","storeOutMessages":true,"fwdInMessages":false,"templateScope":"local","x":616.0195846557617,"y":2164.0041790008545,"wires":[[]]},{"id":"fbc5518f.f9f45","type":"inject","z":"54549b95.190a94","name":"","topic":"","payload":"Feb 09, 2018 13:50:05","payloadType":"str","repeat":"","crontab":"","once":false,"x":401.14630126953125,"y":2305.575101852417,"wires":[["a600589b.f2b9f8"]]},{"id":"ed0a0688.55eb78","type":"ui_group","z":"","name":"Время комната 15","tab":"ab7910af.baccb","order":2,"disp":true,"width":"6"},{"id":"ab7910af.baccb","type":"ui_tab","z":"","name":"Клиенты","icon":"dashboard","order":1}]

尝试此比较两个日期; 创建datetime对象并使用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)); } } } 函数