簡體   English   中英

將一串時間轉換為24小時格式

[英]convert a string of time to 24 hour format

我有一個string ,以這種格式保存開始時間和結束時間8:30AM - 9:30PM我希望能夠剝離AM -PM並將所有時間轉換為24小時格式,以便9:30PM將真的是21:30並且還將兩個時間存儲在兩個不同的變量中,我知道如何將字符串剝離到substrings但我不確定轉換,這是我到目前為止所擁有的。 時間變量從8:30AM - 9:30PM開始。

String time = strLine.substring(85, 110).trim();
//time is "8:30AM - 9:30PM" 

String startTime;               
startTime = time.substring(0, 7).trim();
//startTime is "8:30AM"

String endTime;
endTime = time.substring(9).trim();
//endTime "9:30AM"

工作代碼(考慮到你設法拆分字符串):

public class App {
  public static void main(String[] args) {
    try {
        System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
        System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
        System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
        System.out.println(convertTo24HoursFormat("9:30PM"));  // 21:30
    } catch (ParseException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  // Replace with KK:mma if you want 0-11 interval
  private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
  // Replace with kk:mm if you want 1-24 interval
  private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");

  public static String convertTo24HoursFormat(String twelveHourTime)
        throws ParseException {
    return TWENTY_FOUR_TF.format(
            TWELVE_TF.parse(twelveHourTime));
  }
}

現在我想起來, SimpleDateFormatH h K k可能會令人困惑。

干杯。

您需要使用: SimpleDateFormat
並且可以參考本教程: 使用SimpleDateFormat格式化小時

例:

//create Date object
Date date = new Date();

//formatting hour in h (1-12 in AM/PM) format like 1, 2..12.
String strDateFormat = "h";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

System.out.println("hour in h format : " + sdf.format(date));

我不會重新發明輪子(除非你是作為一個學校項目或其他一些這樣做)。

只需從你的時間戳中獲取一個日期對象,然后你就可以生成任何你想要的格式: SimpleDateFormat

[編輯以滿足您的特定要求]如果你絕對需要使用自己獨特的字符串,那么你會做這樣的事情(我不知道你的字符串是什么樣的......你正在使用像85這樣的偏移量,這意味着沒有任何脫離背景)。

我沒有檢查這個bug,但這大概是你想要的...

myStr = timestampString.toLowerCase(); //something like 8:30am
boolean add12 = (myStr.indexOf("pm") != -1)?true:false;

//convert hour to int
int hour = Integer.parseInt(myStr.split(":")[0]);

int minutes = Integer.parseInt(  myStr.split(":")[1].replaceAll("\\D+","").replaceAll("^0+","") ); //get the letters out of the minute part and get a number out of that, also, strip out leading zeros

int militaryTime = hour + (add12)? 12:0;
if(!add12 && militaryTime == 12)
 militaryTime = 0; //account for 12am

//dont' forget to add the leading zeros back in as you assemble your string

我想提出現代的答案

    DateTimeFormatter twelveHourFormatter = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);

    String time = "8:30AM - 9:30PM";
    String[] times = time.split(" - ");
    LocalTime start = LocalTime.parse(times[0], twelveHourFormatter);
    System.out.println(start.toString());
    LocalTime end = LocalTime.parse(times[1], twelveHourFormatter);
    System.out.println(end.toString());

這打印:

08:30
21:30

我正在使用java.time ,現代Java日期和時間API。 許多其他答案中使用的SimpleDateFormat類已經過時並且總是很麻煩。 java.time比使用1990年代的日期時間類更好。 LocalTime是一個沒有日期(沒有時區)的時間,因此比老式Date更適合您的需求。

鏈接: Oracle教程:日期時間,解釋如何使用java.time

使用Joda Time ,代碼如下所示:

        DateTimeFormatter formatter12 = DateTimeFormat.forPattern("K:mma");
        DateTime begin = formatter12.parseDateTime(beginTime);
        DateTime end = formatter12.parseDateTime(endTime);

        DateTimeFormatter formatter24 = DateTimeFormat.forPattern("k:mma");
        String begin24 = formatter24.print(begin);
        String end24 = formatter24.print(end);

24小時時間增加12到大於12pm的任何時間,因此下午1點是13,依此類推,直到24或12點。 這是sudo代碼:

if(hour <= 12)
{
  hour = hour + 12;
}

當String str =“07:05:45 PM”時,以下所有行都可以使用; 當你調用timeConversion(str)並希望轉換為24小時格式..

 public class TimeConversion {

  private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mm:ssa");
      private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm:ss");


     static String timeConversion(String s) {

         String str = null;
         try {
            str= TWENTY_FOUR_TF.format(
                        TWELVE_TF.parse(s));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

         return str;

     }

    public static void main(String[] args) throws ParseException {

        String str="07:05:45PM";

        System.out.println(timeConversion(str));


    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM