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

后端 未结 2 1680
遇见更好的自我
遇见更好的自我 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题