Java 将 4 位军用时间转换为标准的 12 小时时间格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20342596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:12:20  来源:igfitidea点击:

convert a 4-digit military time into the standard 12 hour time format

javadatetimetimeformatting

提问by Crawsome

What I'm trying to do:

我正在尝试做的事情:

I'm trying to convert a 4-digit military time into the standard 12 hour time format, with a colon and an added PM or AM without the use of importing anything before my code (I'm making a method that requires nothing other than java 101 techniques).

我正在尝试将 4 位数的军用时间转换为标准的 12 小时时间格式,并带有一个冒号和一个添加的 PM 或 AM,而不使用在我的代码之前导入任何内容(我正在制作一个不需要任何东西的方法,除了Java 101 技术)。

My situation:

我的情况:

I have milTime, which I manually change around for now every time I run it(as declared up top, currently at 1100), until I convert it into a method and submit the assignment, in which it will take in milTime, and will return milTimeString for the main program to print. I'm currently using BlueJ as an IDE, (I'm not sure if that's the best one to use?)

我有milTime,每次运行时我都会手动更改它(如上面声明的那样,目前为 1100),直到我将其转换为方法并提交分配,其中它将接受 milTime,并将返回milTimeString 供主程序打印。我目前使用 BlueJ 作为 IDE,(我不确定这是否是最好的使用?)

Example of input and output:

输入输出示例:

If 0056 were given, I would have to return 12:56am. If 1125 were given, I would have to return 11:25am. If 2359 were given, I would have to return 11:59pm.

如果给出 0056,我将不得不在上午 12:56 返回。如果给出 1125,我将不得不在上午 11:25 返回。如果给出 2359,我将不得不在晚上 11:59 返回。

Issues I need help with

我需要帮助的问题

  1. When I execute, my am / pm boolean fails somewhere and it always outputs pm, no matter if I input 11:24 or 23:24.
  2. It's probably obvious I'm working too hard to generate the output, but I don't know an easier way (Other than importing something to do it forme, which I don't want to do).
  1. 当我执行时,我的 am / pm 布尔值在某处失败,它总是输出 pm,无论我输入 11:24 还是 23:24。
  2. 很明显,我正在努力生成输出,但我不知道更简单的方法(除了我导入一些东西,我不想这样做)。

I humbly submit to any criticism on my bloated current code, and any corrections in my long-winded request. I've looked around for alternate answers, and everything involved importing or knowledge beyond me. Thanks for your time so far, and thanks in advance everyone.

我虚心接受对我臃肿的当前代码的任何批评,以及我冗长的请求中的任何更正。我四处寻找替代答案,一切都涉及到我以外的导入或知识。感谢您到目前为止的时间,并提前感谢大家。

public class timeTest
{
    public static void main(String []args)
    {   
        /*Declare my variables*/
        int milTime = 2400;
        String timeString = "";
        boolean pm;

        /*determine AM or PM and convert over 1200 into a clock's digits */
        if (milTime >1259)
        {
            if (milTime <1200)
            {
                pm = false;
            }
            else
            {
                pm = true;
            }
            milTime = (milTime - 1200);
        }
        else
        {
        }

        /*figure out my digits*/
        int fourthDigit = milTime%10;
        milTime = milTime/10;
        int thirdDigit = milTime%10;
        milTime = milTime/10;
        int secondDigit = milTime%10;
        milTime = milTime/10;
        int firstDigit = milTime%10;

        /*build each side of the colon*/
        String hoursString = thirdDigit + "" + fourthDigit;
        String minutesString = firstDigit + "" + secondDigit;

        /*determine if the first digit is zero and if so, omit it*/
        if (firstDigit == 0 )
        {
            minutesString = "" + secondDigit;
        }
        else
        {
        }
        if (secondDigit == 0)
        {
            minutesString = "12";
        }
        else
        {
        }

        /*build the total string and return the result with AM or PM based on conditional boolean.*/
        if (pm = true)
        {
            timeString = (minutesString + ':' + hoursString + "pm");
        }
        else
        {
        }

        if (pm = false)
        {
            timeString = (minutesString + ':' + hoursString + "am");
        }
        else
        {
        }
        System.out.println(timeString);

    }
}

回答by John Kugelman

if (pm = true)
if (pm = false)

A single equal sign is an assignment. You want to do a comparison:

一个等号是一个赋值。你想做一个比较:

if (pm == true)
if (pm == false)

These could also be written more idiomatically as:

这些也可以更惯用地写成:

if (pm)
if (!pm)

That's the main problem. Another is your logic for setting pm. You only need a single ifstatement, with the line subtracting 1200 placed inside the pm = trueblock.

这是主要的问题。另一个是你设置的逻辑pm。您只需要一个if语句,将减去 1200 的行放置在pm = true块内。

if (milTime < 1200)
{
    pm = false;
}
else
{
    pm = true;
    milTime -= 1200;
}

There are a few other bugs that I'll leave to you. I trust these corrections will get you a bit further, at least.

还有一些其他的错误,我会留给你。我相信这些更正至少会让你走得更远。

回答by Josiah Hester

You can do this much, much simpler, using a clever string conversion and SimpleDateFormat, here is the example but parsed in two lines:

您可以使用巧妙的字符串转换和 SimpleDateFormat 来做到这一点,简单得多,这是示例,但解析为两行:

// Heres your military time int like in your code sample
int milTime = 56;
// Convert the int to a string ensuring its 4 characters wide, parse as a date 
Date date = new SimpleDateFormat("hhmm").parse(String.format("%04d", milTime));
// Set format: print the hours and minutes of the date, with AM or PM at the end 
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
// Print the date!
System.out.println(sdf.format(date));
// Output: 12:56 AM

回答by ecbrodie

Your problem is screaming out that you should be using your own custom data formatter. I like using the Joda Time libraryand its DateTimeclass instead of the built-in Java Dateand Calendarclasses. Therefore, instead of SimpleDateFormat, I recommend that you use a DateTimeFormatto create a DateTimeFormatter, which you will then use to convert your String into a DateTime. You will need one DateTimeFormatter for each of input and output. For example:

您的问题是您应该使用自己的自定义数据格式化程序。我喜欢使用Joda Time 库及其DateTime类,而不是内置的 Java DateCalendar类。因此,我建议您使用DateTimeFormat代替SimpleDateFormat来创建DateTimeFormatter,然后您将使用它来将 String 转换为DateTime。每个输入和输出都需要一个 DateTimeFormatter。例如:

String rawTimestamp = "2300"; // For example
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HHmm");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("hh:mm a");
DateTime dateTime = inputFormatter.parseDateTime(rawTimestamp);
String formattedTimestamp = outputFormatter.print(dateTime.getMillis());
return formattedTimestamp;

Try this out!

试试这个!

回答by Jeffery Brannon

public static String convert24HourToAmPm(String time) {

    if (time == null)
        return time;

    // Convert time where time is like: 0100, 0200, 0300....2300...
    if (time.length() == 4 && Helper.isInteger(time)) {
        String hour = time.substring(0,2);
        String minutes = time.substring(2,4);
        String meridian = "am";

        if (hour.substring(0,2).equals("00")) {
            hour = "12";
        } else if (hour.substring(0,1).equals("1") || hour.substring(0,1).equals("2")) {
            meridian = "pm";
            Integer militaryHour = Integer.parseInt(hour);
            Integer convertedHour = null;

            if (militaryHour > 12) {
                convertedHour = (militaryHour - 12);

                if (convertedHour < 10)
                    hour = "0" + String.valueOf(convertedHour);
                else
                    hour = String.valueOf(convertedHour);
            }
        }

        time = hour + ":" + minutes + " " + meridian;
    }

    // TODO - Convert time where time is like 01:00...23:00...

    return time;
}