0

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

3
  • 2
    Convert.ToChar(first_Char) turns a integer to a character with the corresponding character code, not one that has the equivalent numeral face-value. This the same reason as to why Char.GetNumericValue must be used instead of Convert.ToInt32: so what is the 'opposite' of Char.GetNumericValue? Commented Oct 11, 2018 at 16:59
  • Are you just trying to convert a 12 hour time into 24 hour time? Because there are way easier ways of doing this... Commented Oct 11, 2018 at 17:03
  • manipulate DateTimes using the DateTime functions. Commented Oct 11, 2018 at 17:23

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah,but is there any way to replace a index of character array with int value?
@NaveenKumar Why do you want to do this? It does not make sense given the context indicated in your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.