1

I am developing a Console application for converting the time from 12 hours format to 24 hours format:

input: 02:03:34PM expected output:14:03:34

But I am getting 14:3:34 Below is my code snippet:

string[] arr_temp = Console.ReadLine().Split(':');

string time =  arr_temp[2].ToUpper().Contains("AM") ? "AM" : "PM";

string sec=string.Empty;

for (int i = 0; i < 2; i++)
{
   sec+= arr_temp[2][i];
}

int _hour = Int32.Parse(arr_temp[0])==0?0: Int32.Parse(arr_temp[0]); 

int _minute = Int32.Parse(arr_temp[1]) == 0 ? 0 : Int32.Parse(arr_temp[1]); 

int _sec = Int32.Parse(sec)==0?0: Int32.Parse(sec);

_hour = (time == "PM") ? _hour += 12 : _hour += 0;

_hour = (_hour < 10) ? '0' + _hour : _hour;

_minute = (_minute < 10) ? '0' + _minute : _minute;

_sec = (_sec < 10) ? '0' + _sec : _sec;

I am not getting the expected output. Please suggest.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215

6 Answers6

3

Seems a bit complicated to me as there's a much simpler way to display your DateTime variable to either 12 or 24 hours format.

First you will have to convert your string to a valid DateTime object. There are parsing methods which you can use, but you will have first to validate the input string returned by the user as a valid date.

Use the following code in order to convert your string to DateTime:

string dateString = "03/01/2009 10:00 AM";
DateTime date = DateTime.Parse(dateString); 

DateTime.Parse will throw an exception if input string is not in the right format. In order to make sure this doesn't happen, use DateTime.TryParse instead.

string dateString = "03/01/2009 10:00 AM";
DateTime dateTime;
if (DateTime.TryParse(dateString , out dateTime))
{
    Console.WriteLine(dateTime);
}

Then you can display the DateTime variable and format it the way you want.

DateTime dateTime = DateTime.Now;
string str12Format = dateTime.ToString("hh:mm:ss tt"); //12 hours format
string str24Format = dateTime.ToString("HH:mm:ss tt"); //24 hours format
Tommy Naidich
  • 752
  • 1
  • 5
  • 23
  • 2
    Actually OP has datetime as inout from console in a given format, so you need to create the `DateTime`-instance in front. – MakePeaceGreatAgain Apr 20 '17 at 06:37
  • @HimBromBeere The example I have provided demonstrates the usage of the ToString method in order to format the DateTime. Of course edits will have to be made to the code before implementation, but that's up to OP. – Tommy Naidich Apr 20 '17 at 06:38
  • @MickyD I've updated my answer with an explanation on how to convert the initial string to a DateTime object as well. – Tommy Naidich Apr 20 '17 at 07:00
1

_hour in your code is an integer. You cannot concatenate string to an integer. But the reverse is possible.

So you should use this instead :

int _hour = Int32.Parse(arr_temp[0])==0?0: Int32.Parse(arr_temp[0]); 
int _minute = Int32.Parse(arr_temp[1]) == 0 ? 0 : Int32.Parse(arr_temp[1]); 
int _sec = Int32.Parse(sec)==0?0: Int32.Parse(sec);

_hour = (time == "PM") ? _hour += 12 : _hour += 0;

String _hourS = (_hour < 10) ? '0' + _hour : _hour;
String _minuteS = (_minute < 10) ? '0' + _minute : _minute;
mrid
  • 5,782
  • 5
  • 28
  • 71
  • 1
    What's wrong with the `Parsexxx()` methods in `DateTime`? –  Apr 20 '17 at 06:54
  • @MickyD nothing's wrong with using them and they would work just fine. I wrote this solution just to inform the OP that wrong typecasting can cause errors in strongly typed languages. – mrid Apr 20 '17 at 08:56
1

Try using DateTime.TryParseExact followed by ToString, do not repeat Microsoft and reinvent the wheel:

  string source = Console.ReadLine();
  DateTime date;

  // DateTime.TryParseExact supports many formats; that's why "12:34AM" will be accepted
  // DateTimeStyles.AllowWhiteSpaces let us be nice and allow, say "11 : 34 : 47 PM"
  if (DateTime.TryParseExact(
        source, 
        new string[] {"h:m:stt" , "h:mtt", "htt", "H:m:s", "H:m", "H"}, 
        CultureInfo.InvariantCulture, // or CultureInfo.CurrentCulture
        DateTimeStyles.AssumeLocal | DateTimeStyles.AllowWhiteSpaces, 
        out date)) 
    Console.WriteLine(date.ToString("HH:mm:ss"));
  else
    Console.WriteLine($"Sorry, {source} is not a valid date");
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Just pass you input

    public static TimeSpan ConvertToAMPM(DateTime date)
    {
        return TimeSpan.Parse(date.ToString("h:mm tt", 
        CultureInfo.InvariantCulture));
    }

    public static TimeSpan ConvertTo24Hour(string time)
    {
        var cultureSource = new CultureInfo("en-US", false);
        var cultureDest = new CultureInfo("de-DE", false);
        var dt = DateTime.Parse(time, cultureSource);
        return TimeSpan.Parse(dt.ToString("t", cultureDest));
    }
Ahmed
  • 26
  • 2
0

The other answers so far mostly address the example of handling a DateTime, but they do not explain why your code breaks.

What you are trying to do is to add a leading zero to an int variable just as you'd do it with a string.

The problem is that the internal representation of an int is just the number itself, and it carries no format information. As such, it cannot store information about leading zeros. This can only be done by using string, which do not represent a number but a collection of characters.

So the essence is that you need to see the data and its representation as two separate things. In general it's best to keep the data in its native form and only convert it at the very last moment when needed for display. This also allows you to respect cultural differences of the display representation.

Many basic data types (including int and DateTime etc.) are formattable. What this means is that they can be converted to a string (display) representation with respect to a pattern describing how this representation should be. For int, such a pattern can define that it needs to have a leading zero like so:

string _hourDisplay = _hour.ToString("00");
Lucero
  • 59,176
  • 9
  • 122
  • 152
0

Hi Nishank, Use this code :

string[] arr_temp = Console.ReadLine().Split(':');

string time = arr_temp[2].ToUpper().Contains("AM") ? "AM" : "PM";
string sec = arr_temp[2].Substring(0, 2);

string _hour = "";
if (time == "PM" && Int32.Parse(arr_temp[0]) < 12)
    _hour = (Int32.Parse(arr_temp[0]) + 12).ToString("D2");
else if (time == "AM" && Int32.Parse(arr_temp[0]) == 12)
    _hour = "00";
else
    _hour = Int32.Parse(arr_temp[0]).ToString("D2");

string _minute = Int32.Parse(arr_temp[1]) == 0 ? "00" : Int32.Parse(arr_temp[1]).ToString("D2"); 

string _sec = Int32.Parse(sec) == 0 ? "00" : Int32.Parse(sec).ToString("D2");

string outputTime = _hour + ":" + _minute + ":" + _sec + "" + time;