Search code examples
c#datetimecalendarglobalizationdatetime-format

Display Persian time in format hh:mm


I am using a persian calender on my application , i am using that code :

using System.Globalization;

[...]

PersianCalendar pc = new PersianCalendar();
DateTime thistime = DateTime.Now;
string persiantimenow = pc.GetHour(thistime) + ":" + pc.GetMinute(thistime);

Console.WriteLine(persiantimenow);

It is 12:35AM now , so the output is : 0:33 , but i want it to be 00:33

I tried using :

string persiantimenow = pc.GetHour(thistime.ToString("hh")) + ":" + pc.GetMinute(thistime.ToString("mm"));

It gave me error so i used the next one , but also gave same error

string thistime_Hour = thistime.ToString("HH");
string thistime_minute = thistime.ToString("MM");

string persiantimenow = pc.GetHour(thistime_Hour) + ":" + pc.GetMinut(thistime_minute);

But i get Error :

Argument 1: cannot convert from 'string' to 'System.DateTime'

EDIT 1 [I have figured a tricky solution]

if (pc.GetHour(thistime) < 12)
{
     string persiantimenow = "0" + pc.GetHour(thistime) + ":" + pc.GetMinute(thistime);
     Console.WriteLine(persiantimenow);
}

It is not what i needed but it solves the issue.

EDIT 2 [L.B solved it for me] Here is the solution :

string persiantimenow = pc.GetHour(thistime).ToString("00") + ":" + pc.GetMinute(thistime).ToString("00");

Solution

  • Ideally, you'd use a DateTimeFormatInfo which has the Calendar property set to be the PersianCalendar. However, from the docs:

    Your application should not use a PersianCalendar object as the default calendar for a culture. The default calendar is specified by the CultureInfo.Calendar property and must be one of the calendars returned by the CultureInfo.OptionalCalendars property. Currently, the PersianCalendar class is not an optional calendar for any culture supported by the CultureInfo class and consequently cannot be a default calendar.

    That makes it hard to use without fudging it, basically :(

    For the hour/minute though, does the calendar actually matter? I'm very aware that different calendars treat different dates differently, but do they treat times differently? Can you not just use the invariant culture, for time fields?