Java - 12小时到24小时格式(hackerrank)

时间:2018-05-26 19:02:02

标签: java time time-format

注意: 我在2天内尽可能多地查看这是否重复。如果我错过了什么,我道歉。这个问题是要找出我尝试解决方案的问题,而不是现有的解决方案之一。

我的问题

我试图解决Java 7中hackerrank的一些问题,我遇到了问题陈述的时间转换问题:

问题: &#34;给定时间为AM / PM格式,将其转换为军事(24小时)时间。&#34; < / p>

示例输入 下午7点05分45秒

示例输出 19时05分45秒

我查看了涉及库的解决方案(例如java.text.SimpleDateFormat,Calendar等),但我试图在没有它们的情况下独自完成。我在这里遇到的问题是我的解决方案在某些测试用例上失败但正在处理其他测试用例。简而言之,这不是正确的解决方案。我看到其他解决方案,但我想知道为什么我的失败是正确的答案。能告诉我这会失败以及如何纠正它,请你帮助我吗?

我看到的一些解决方案是:

Conversion from 12 hours time to 24 hours time in java

Convert 12 hours to 24 hours

我的代码在这里:

import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

public class Solution {

    static String timeConversion(String s) {

        //get the string into an array using : as a separator
        String[] time_array = s.split(":");

        //military_time variable to be returned
        String military_time = new String();

        //final HH part
        String hh_final = new String();
        //Rest after HH to be concatenated to get military_time
        String rest = new String();


        StringBuilder REST_mil_builder = new StringBuilder();
        for (int i = 2; i < 8; i++) {
            REST_mil_builder.append(s.charAt(i));
        }
        //"rest" basically gets everything after HH excluding AM/PM, so 01:03:40PM would have a "rest" value of ":03:40"
        rest = REST_mil_builder.toString();

        int hh = Integer.parseInt(time_array[0]);
        String AMPM_contains = time_array[2];

        //converting if the last piece after the split contains "PM"
        if (AMPM_contains.contains("PM")) {
            hh = hh + 12;
            hh = hh == 24 ? 0 : hh;
        }

        //converting hh to have a 0 before it because when it is an integer 01 will be just 1 which we don't want
        StringBuilder hh_build = new StringBuilder();
        if (hh >= 0 && hh <= 9) {
            hh_build.append("0");
            hh_build.append(hh);
            hh_final = hh_build.toString();
        } else {
            hh_build.append(hh);
            hh_final = hh_build.toString();
        }

        //military time concatenation
        military_time = hh_final + rest;
        //Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock
        military_time = s == "12:00:00AM" ? "00:00:00" : military_time;
        //Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
        military_time = s == "12:00:00PM" ? "12:00:00" : military_time;

        return military_time;

    }

    private static final Scanner scan = new Scanner(System.in);

    public static void main(String[] args)  {

        //tried several 12 hour time formats here
        String result = timeConversion("01:30:59PM");
        System.out.println(result);
    }
}

7 个答案:

答案 0 :(得分:3)

您的代码失败,因为它无法正确处理小时12,即12:xx:xxAM应映射到00:xx:xx,而12:xx:xxPM应映射到12:xx:xx,如answer by Ole V.V.

不是试图修复过于复杂的代码,而是使用SimpleDateFormat,这是一种不同的方法。

将前2位数字解析为数字。如果数字为12,则将其设置为0.这样做的一种技巧方法是使用模12。如果输入以PM结尾,则添加12.现在重建字符串,用新数字替换前2位数字,然后删除上午/下午后缀。

像这样:

public static String timeConversion(String s) {
    int hour = Integer.parseInt(s.substring(0, 2)) % 12;
    if (s.endsWith("PM"))
        hour += 12;
    return String.format("%02d", hour) + s.substring(2, 8);
}

使用Ole V.V。

的测试
System.out.println(timeConversion("12:30:59AM"));
System.out.println(timeConversion("11:30:59AM"));
System.out.println(timeConversion("12:30:59PM"));
System.out.println(timeConversion("11:30:59PM"));

输出

00:30:59
11:30:59
12:30:59
23:30:59

答案 1 :(得分:1)

    System.out.println(timeConversion("12:30:59AM"));
    System.out.println(timeConversion("11:30:59AM"));
    System.out.println(timeConversion("12:30:59PM"));
    System.out.println(timeConversion("11:30:59PM"));

预期产出:

00:30:59
11:30:59
12:30:59
23:30:59

观察输出:

12:30:59 (wrong)
11:30:59 (correct)
00:30:59 (wrong)
23:30:59 (correct)

编辑:简而言之,您的代码似乎没有考虑到12小时时刻12小时不同。你可能会说它被用作00小时。我不认为修复你的程序会太难,所以我会让你有第一枪的乐趣。如果您需要提示,请在评论中进行跟进。我们都很乐意提供帮助。

另外,您在代码中的三个位置使用new String()。我认为这是多余的,因为你从来没有使用创建的空字符串。

答案 2 :(得分:0)

请尝试static String timeConversion(String s) function。我希望这会对您有所帮助。

static String timeConversion(String s) {

        String[] time = s.split(":");

        String hours = time[0];
        String minutes = time[1];
        String seconds = time[2].substring(0, 2);
        String dayEve = time[2].substring(2, 4);
        if (dayEve.equals("AM")) {
            return ((hours.equals("12") ? "00" : hours) + ":" + minutes + ":" + seconds);
        } else {
            return ((hours.equals("12") ? hours : (Integer.parseInt(hours) + 12)) + ":" + minutes + ":" + seconds);
        }

    }

主要逻辑是: -

如果&#39; AM&#39;然后将hours == 12小时设置为00,否则不会更改hours

如果&#39; PM&#39;并且hours == 12然后不要更改hours其他小时设置为hours = hours+12

答案 3 :(得分:0)

请使用SimpleDateFormat

public static String to24Time(String str) throws ParseException {
    DateFormat df12 = new SimpleDateFormat("hh:mm:ssa", Locale.US);
    DateFormat df24 = new SimpleDateFormat("HH:mm:ss", Locale.US);
    return df24.format(df12.parse(str));
}

<强> P.S。 这是来自Hackerrank的任务:算法/预热/时间转换

  1. 没有任何说明禁止使用java内部类进行时间分析,你必须手动完成。
  2. 提供的答案为此任务提供 100%测试通过
  3. <强> P.P.S 如果您不想使用SimpleDateTime,这是如何使用正则表达式的示例。请注意,我没有提供输入sting的完整验证;在某些情况下(例如非法的12小时时间格式,如21:17:17 PM),它会返回非法结果而不是例外:

    public static String to24Time(String str) throws ParseException {
        final Pattern TIME_12 = Pattern.compile("(?<hour>\\d{2}):(?<minute>\\d{2}):(?<second>\\d{2})(?<part>am|pm)");
        Matcher matcher = TIME_12.matcher(str.toLowerCase());
    
        if (matcher.matches()) {
            int hour = Integer.parseInt(matcher.group("hour"));
            return ("pm".equals(matcher.group("part")) ? hour + 12 : hour) + ":" + matcher.group("minute") + ':' + matcher.group("second");
        }
    
        return null;
    }
    

答案 4 :(得分:0)

这是我使用JavaScript解决的方法:

function timeConversion(s) {


    var res;

    var pos = s.substring(-2, 8);

    var split = pos.split(':');

    if (split[0] == 12 && s.endsWith('AM')) {
        res = '00' + ':' + split[1] + ':' + split[2];

    } else if (split[0] == 12 && s.endsWith('PM')) {
        res = '12' + ':' + split[1] + ':' + split[2];

    } else if (split[0] < 12 && s.endsWith('AM')) {
        res = split[0] + ':' + split[1] + ':' + split[2];

    } else if (split[0] < 12 && s.endsWith('PM')) {
        var add = Number(split[0]) + 12;
        res = add + ':' + split[1] + ':' + split[2];
    }
    return res;
}

答案 5 :(得分:0)

static String timeConversion(String s) {
    int hrs = 12;
    String[] split = s.split(":");
    String originalAMPM = split[2].substring(2,4);
    String hours = split[0]; String minutes = split[1]; String seconds = split[2].substring(0,2);
    if(originalAMPM.equals("PM")) {
        if(!hours.equals("12"))
            hrs = Integer.parseInt(hours) + 12;
        return hrs + ":" + minutes + ":" + seconds;
    }
    else {
        if(hours.equals("12"))
            hours = "00";
        return hours + ":" + minutes + ":" + seconds;
    }
}
   

答案 6 :(得分:0)


#!/bin/python3

import os
import sys
import re
#
# Complete the timeConversion function below.

def timeConversion(s):

    if s[len(s)-2:]=='PM':
        
        if s[0] == '0':
            s1=s.strip('0')
            sn = s1.strip('PM')
            return sn.replace(sn[0],str(int(sn[0])+12))

        elif s[0:2]=='12':
            
            return s.strip('PM')
        else:
            sn = s.strip('PM')
            return sn.replace(sn[0:2],str(int(sn[0:2])+12)) 

    else: #s[len(s)-2:]=='AM':

        if s[0:2]=='12':
            s1=s.strip('AM')
            return s1.replace(s[0:2],'00')
        else:
            return s.strip('AM') 
                     
        

    
if __name__ == '__main__':
    f = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = timeConversion(s)

    f.write(result + '\n')

    f.close()
相关问题