asp.net c#从军事时间到标准时间的更改

本文关键字:标准时间 时间 net asp | 更新日期: 2023-09-27 18:09:24

我有这个:

StringBuilder sb = new StringBuilder(time.Text);
if (DateTime.Parse(time.Text) > DateTime.Parse("12:00:00 AM")
    && DateTime.Parse(time.Text) < DateTime.Parse("11:59:59 AM"))                                    
{
    time.Text = time.Text + " AM";
}
else
{
    time.Text = time.Text + " PM";
}

我现在的时间是下午16:34,

我想让它显示04:34 PM

asp.net c#从军事时间到标准时间的更改

简写

string strTime = DateTime.Now.ToString(@"hh':mm':ss tt");

在你的例子中,它将是:

 time.Text=DateTime.Parse(time.Text).ToString(@"hh':mm':ss tt");

,并确保自定义格式,如HH是24小时格式,MM是月

try

time.Text = DateTime.Parse(time.Text).ToString("hh:mm:ss tt");
 public static string FormattedTime(this TimeSpan TimeIn24Hours)
    {
        String TimeIn12Hours = string.Empty;
        if (TimeIn24Hours != null)
        {
            TimeIn12Hours = DateTime.MinValue.AddHours(TimeIn24Hours.Hours).AddMinutes(TimeIn24Hours.Minutes).ToString("hh:mm");
        }
        return TimeIn12Hours;
    }
private void UpdateTime()
{
    int hours, mins, sec;
    string TimeofDate = "AM";
    currentTime = DateTime.Now;
    hours = Convert.ToInt32(currentTime.Hour.ToString());
    mins = Convert.ToInt32(currentTime.Minute.ToString());
    sec = Convert.ToInt32(currentTime.Second.ToString());
    // lbCurrentTime.Text = currentTime.ToLongTimeString();
    // label2.Text = hours.ToString() + ":" + mins.ToString() + ":" + sec.ToString();
    if (hours >= 12)
    {
        hours = hours - 12;
        TimeofDate = "PM";
    }
    else TimeofDate = "AM";
    lbCurrentTime.Text = hours.ToString() + ":" + mins.ToString() + ":" + sec.ToString()+" "+TimeofDate;
}