Naveen Kumar
Naveen Kumar

Reputation: 13

Convert int variable value to char array value in c#?

I tried it my way, want to know where am i going wrong and to know how to replace int variable value to one of the index of char array?

string time = "07:05:45PM";
string result = string.Empty;
char[] time_Char = time.ToCharArray();
int first_Char = (int)Char.GetNumericValue(time_Char[0]) + 1;
int second_Char = (int)Char.GetNumericValue(time_Char[1]) + 2;

time_Char[0] = Convert.ToChar(first_Char);
time_Char[1] = Convert.ToChar(second_Char);

for (int i = 0; i < time_Char.Length; i++)
{
 result += time_Char[i];
}

Console.WriteLine(result);

Output - :05:45PM

Expected Output - 19:05:45PM

Upvotes: 0

Views: 158

Answers (1)

maccettura
maccettura

Reputation: 10818

Are you just trying to turn a 12 hour time into a 24 hour time? It is not super clear from your question because obviously AM/PM are irrelevant when you are dealing with 24 time...

However if this is what you are trying to do there are way easier ways of doing this. You should just parse your input string into a new DateTime object, then you can output that date/time using custom formatting when calling .ToString():

string time = "07:05:45PM";

DateTime output;
if(DateTime.TryParse(time, out output))
{
    Console.WriteLine(output.ToString("HH:mm:sstt"));
}

This would output: 19:05:45PM

Fiddle here

Upvotes: 1

Related Questions