-1

I wrote this code to convert 12H time to 24H time but with an input:

07:05:45pm

I get output as:

07:05:45

Here's the code

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

public class Demo
{
static String timeConversion(String s)
{
    // Complete this function
    char a = 'a';
    char l = 0, m = 0;
    int l1 = 0, m1 = 0;
    final int RADIX = 10;
    char p = 'p';
    String str = new String();
    char t1 = 0;
    int t2 = 0;
    char arr[] = new char[10];
    arr = s.toCharArray();
    int a1 = Character.getNumericValue(arr[0]);
    int a2 = Character.getNumericValue(arr[1]);
    int t = (10*a1)+(a2);
    char _1 = '1', _2 = '2';
    if(arr[8]==p)
    {
        if((arr[0]==(_1))&&(arr[1]==(_2)))
        {
            char arr1[] = new char[8];
            for(int i = 0; i < 8; i++)
                arr1[i] = arr[i];
            str=String.copyValueOf(arr1);
        }
        else
        {
            t2 = t + 12;
            l1 = (t2%10);
            t2/=10;
            m1 = (t2%10);
            m = Character.forDigit(m1, RADIX);
            l = Character.forDigit(l1, RADIX);
            arr[1] = l;
            arr[0] = m;
            char arr1[] = new char[8];
            for(int i = 0; i < 8; i++)
                arr1[i] = arr[i];
            str=String.copyValueOf(arr1);
        }
    }
    else
        {
            char arr1[] = new char[8];
            for(int i = 0; i < 8; i++)
                arr1[i] = arr[i];
            str=String.copyValueOf(arr1);
        }
    return str;

}

public static void main(String[] args)
{
    //Scanner in = new Scanner(System.in);
    //String s = in.next();
    String s = "07:05:45PM";
    String result = timeConversion(s);
    System.out.println(result);
}
}    

As you can see I've hard coded the input becuse intellij won't allow me to pass command line arguments so I would also like to know how to pass command line argumnets in intellij.

Also, it would be really helpful if you would suggest me some good coding habits after looking at my code.

Karan
  • 11
  • 1
  • 5
  • 1
    Are you looking to fix this code, or a simple way to change date format ? – c0der Sep 11 '17 at 16:09
  • I want to fix this code that's the primary motive though any other way to solve the problem is also welcome – Karan Sep 11 '17 at 16:23
  • Regarding your question for what to do better: comment each block of your algorithm (what is the purpose), you mention you use `intelliJ` so use the `Reformat Code` option (equal intent, spacing), better variable naming (already mentioned in an answer), use debuggers to find errors (that would easily help to identify your problem here - case sensitive matching). – Philipp Sep 11 '17 at 16:35

4 Answers4

3

tl;dr

LocalTime
    .parse("07:05:45PM", DateTimeFormatter.ofPattern("hh:mm:ssa"))
    .toString()

Java new Date/Time API

One alternative is to use the built-in date/time API's.

If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).

The code below works for both. The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

As we're dealing with times only (hour/minute/second), you can use a LocalTime. You'll also need a DateTimeFormatter with the specified format to parse it:

String s = "07:05:45PM";
// formatter with format "hour:minute:second" followed by "AM/PM"
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm:ssa");
// parse and get the result as a String
String result = LocalTime.parse(s, fmt).toString();
System.out.println(result);

The output will be:

19:05:45


It's much better to use the built-in API's than to reinvent the wheel (unless you're coding only for learning purposes).

If you want the output in a different format, just create another DateTimeFormatter with the desired pattern and use the format method. Check the javadoc for more info about all the available patterns.

Community
  • 1
  • 1
  • I would add a heading to summarize this correct Answer: # `LocalTime.parse(…).toString()` – Basil Bourque Sep 11 '17 at 16:14
  • @BasilBourque I usually don't add summaries, although it seems a good idea. Updated, thanks! –  Sep 11 '17 at 16:19
  • 1
    @Hugo Mann, I'll have to say you've got some serious knowledge of Java classes and methods and yes I'm coding to learn but still, your answer was a great help will always use your method when handling time in java :) – Karan Sep 11 '17 at 17:00
  • Thanks, @Karan. If this answer was helpful and (only if) solved your problem and you consider it the best solution among all the answers, you can accept it (check [this link that explains how it works](https://stackoverflow.com/help/someone-answers)) - You can also upvote it [when you have enough rep to do it](https://stackoverflow.com/help/privileges/vote-up). But don't feel obliged to do so (do it only if this solved your problem and you consider it to be the best solution among all the answers, as explained in the link). If you find none of the answers useful, you don't need to accept any –  Sep 11 '17 at 17:07
  • @Hugo FYI, I have seen very good response to adding a `tl;dr` section with code summary/excerpt on [my own answers](https://stackoverflow.com/users/642706/basil-bourque?tab=answers). – Basil Bourque Sep 11 '17 at 20:37
0

I wrote this code to convert 12H time to 24H time but with an input:

The fist thing I would check for you is in the condition arr[8]==p; here p='p' from a previous line, but in the string this array index is passing 'P' which is a separate char due to capitalization.

Also, it would be really helpful if you would suggest me some good coding habits after looking at my code.

As to you second point about suggesting habits, comment, comment, comment. Comments will help in explaining what you are doing to another end user and, perhaps more importantly, yourself. It's a bit like Rubber Duck Debugging. Secondly, give your variables more intuitive names; your variable names are all very generic and it takes time to refer back to declarations to see what is going on.

Philipp
  • 1,289
  • 1
  • 16
  • 37
0

You are providing String s = "07:05:45PM"; but considering use with char p = 'p', you should consider upper as well lower case meaning both 'p' and 'P'. Also, you have not considered 12:XX am time. e.g. 12:05 AM should show 00:05.

For providing argument to inteliJ idea, refer this.

Windows, Linux, some Macs:

ALT+SHIFT+F10, Right, E, Enter, Tab, enter your command line parameters, Enter

user2044822
  • 135
  • 6
0
import java.text.SimpleDateFormat;
import java.util.Date;

public class HelloWorld
{
    public static void main(String [] args) throws Exception
    { 
        SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); 
        System.out.println(displayFormat.format(parseFormat.parse("07:05 PM")));
    }
}
Karan Shaw
  • 1,206
  • 10
  • 11
  • Please don’t teach the young ones the long outdated classes `SimpleDateFormat` and `Date`. While I do agree in using a standard library rather than reinventing the wheel, today we have so much better. See [Hugo’s answer](https://stackoverflow.com/a/46160016/5772882). – Ole V.V. Sep 12 '17 at 14:04
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 08 '18 at 23:00