Jan 29, 2019

C# Convert 24 hour format to 12 hour format in English and Arabic

I was writing a Web API to return a Time in both English and Arabic. My expectation was really simple. In my database table I had time as 24 hour format. So I wanted to return it in 12 hour format both in English and Arabic. Lets see what it looks like.

Start Time in 24 hour format(Database): 1130
End Time in 24 hour format(Database): 1430
12 hour format in English : 11:30 AM - 02:30 PM
12 hour format in Arabic:  م 02:30 - ص 11:30

To Convert to English is very straight forward.


1
2
3
4
5
6
7
private string Convert24To12HourInEnglish(string pStartTime, string pEndTime)
{
    DateTime startTime = new DateTime(2018, 1, 1, int.Parse(pStartTime.Substring(0, 2)), int.Parse(pStartTime.Substring(2, 2)), 0);
    DateTime endTime = new DateTime(2018, 1, 1, int.Parse(pEndTime.Substring(0, 2)), int.Parse(pEndTime.Substring(2, 2)), 0);

    return startTime.ToString("hh:mm tt") + " - " + endTime.ToString("hh:mm tt");
}


But when it comes to Arabic you need to format little. because when you add an Arabic text its automatically format to Right to Left(That's how Arabic language reads). 

We need to tell the string that we concatenate Left to Right using ((Char)0x200E).ToString()

Lets see how we can achieve that.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private string Convert24To12HourInArabic(string pStartTime, string pEndTime)
{
    DateTime startTime = new DateTime(2018, 1, 1, int.Parse(pStartTime.Substring(0, 2)), int.Parse(pStartTime.Substring(2, 2)), 0);
    DateTime endTime = new DateTime(2018, 1, 1, int.Parse(pEndTime.Substring(0, 2)), int.Parse(pEndTime.Substring(2, 2)), 0);

    pStartTime = startTime.ToString("hh:mm tt");
    pEndTime = endTime.ToString("hh:mm tt");

    var lefttoright = ((Char)0x200E).ToString();
    string formattedText = (pEndTime.IndexOf("AM") > 0 ? "ص" : "م") + lefttoright + endTime.ToString("hh:mm") + " - " + (pStartTime.IndexOf("AM") > 0 ? "ص" : "م") + lefttoright + startTime.ToString("hh:mm");

    return formattedText;
}


That's it. now you have the two methods to Convert 24 Hour format time to 12 Hour format time in both English and Arabic.

No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...