有问题的代码如下:

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 ?


当前回答

如果你想给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 

其他回答

DateTime应该始终在“美国”(格里高利历)的内部。所以如果你这样做

var str = dateTime.ToString(@"yyyy/MM/dd hh:mm:ss tt", new CultureInfo("en-US"));

你可以少写几行就能得到你想要的东西。

@Andy的回答是ok。但如果你想显示时间而不是24小时格式,你可以这样做

string dateTime = DateTime.Now.ToString("hh:mm:ss tt", CultureInfo.InvariantCulture);

之后,你应该得到“10:35:20 PM”或“10:35:20 AM”这样的时间

如何:

dateTime.ToString("tt", CultureInfo.InvariantCulture);

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

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