Issue: Convert 12hr clock to 24 hrs, then reverse it back

后端 未结 2 1679
遇见更好的自我
遇见更好的自我 2021-01-27 04:05

I am a c# beginner. I am writing a web application in MVP, and having trouble to convert 12 hr clock to 24 hr clock. So, there are three dropdown boxes (hour, mins, AM/PM) When

相关标签:
2条回答
  • 2021-01-27 04:45

    Below is a code sample of how you could convert the time to 24 hour format if the time is in PM. You could do the reverse, i.e. converting from 24 hours format to 12 hours format along similar lines as in the sample below & hence leave that to you. In case you want any help there, let me know.

    Code Sample: 12 hours to 24 hours

    public string sunOpenTime
    {
        get
        {
            int hours = 0;
            int mins = 0;
            if (int.TryParse(ddlSundayOpenTimeHr.Text, hours) && int.TryParse(ddlSundayOpenTimeHr.Text, mins))
            {
                TimeSpan ts;
                if (ddlSundayFrom.SelectedValue == "PM")
                {
                    ts = new TimeSpan(hours + 12, mins, 0);   
                }
                else
                {
                    ts = new TimeSpan(hours, mins, 0);
                }
                return ts.ToString();//There are numerous ways to format the time string, check link below.
            }
            else
            {
                    return "Invalid Time";//Indicatory msg - Handle it the way you want.
            }
        }
    
        set
        {
            sunOpenTime = value;
        }
    }
    

    P.S: Link for formatting time string is here

    EDIT 1:

    You may consider moving the conversion code (12 hr to 24 hr) from the getter to a function or in any code block that suits you. In essence I'm trying to convey only the method of conversion from 12 hr to 24 hrs.

    0 讨论(0)
  • 2021-01-27 04:45

    There is some simple math you can do to convert between hours of a 24-hour clock and hours of a 12-hour clock.

    // 24-hour clock to 12-hour clock
    int hours12 = (hours24 + 11) % 12 + 1;
    string meridiem = hours24 < 12 ? "AM" : "PM";
    
    // 12-hour clock to 24-hour clock
    int hours24 = meridiem == "AM"
      ? (hours12 == 12 ? 0 : hours12)
      : (hours12 == 12 ? 12 : hours12 + 12);
    
    0 讨论(0)
提交回复
热议问题