简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM