有问题的代码如下:

public static string ChangePersianDate(DateTime dateTime)
{
    System.Globalization.GregorianCalendar PC = new System.Globalization.GregorianCalendar();
    PC.CalendarType = System.Globalization.GregorianCalendarTypes.USEnglish;
    return
    PC.GetYear(dateTime).ToString()
    + "/"
    + PC.GetMonth(dateTime).ToString()
    + "/"
    + PC.GetDayOfMonth(dateTime).ToString()
    + ""
    + PC.GetHour(dateTime).ToString()
    + ":"
    + PC.GetMinute(dateTime).ToString()
    + ":"
    + PC.GetSecond(dateTime).ToString()
    + " "
    ????????????????
}

如何从dateTime值中获得AM/PM ?


当前回答

另一种选择是更改用于获得正确格式的默认区域性。这样做的好处是,新格式将在整个代码中使用。

CultureInfo.CurrentCulture = new CultureInfo("Fr-fr");
Console.WriteLine(DateTime.Now.ToString("t")); // 14:08

var customCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
customCulture.DateTimeFormat.AMDesignator = "am";
customCulture.DateTimeFormat.PMDesignator = "pm";
customCulture.DateTimeFormat.ShortTimePattern = "HH:mm tt";
CultureInfo.CurrentCulture = customCulture;

Console.WriteLine(DateTime.Now.ToString("t")); // 14:08 pm

其他回答

您可以用这种方法进行测试

Console.WriteLine(DateTime.Now.ToString("tt "));

输出如下所示:

AM

or

PM

比如bool isPM = GetHour() > 11。但如果您想将日期格式化为字符串,则不需要自己执行此操作。使用日期格式函数。

如果你想给LongDateString Date添加时间,你可以这样格式化它:

    DateTime date = DateTime.Now;
    string formattedDate = date.ToLongDateString(); 
    string formattedTime = date.ToShortTimeString();
    Label1.Text = "New Formatted Date: " + formattedDate + " " + formattedTime;

输出:

New Formatted Date: Monday, January 1, 1900 8:53 PM 

来自:http://www.csharp-examples.net/string-format-datetime/

string.Format("{0:t tt}", datetime);  // -> "P PM"  or "A AM"
+ PC.GetHour(datetime) > 11 ? "pm" : "am"

对于你的例子,但是有更好的方法格式化datetime。