Munashe Tsododo
Munashe Tsododo

Reputation: 247

Parsing time in C#

How do you parse time only in C#? For example if the user enters "12:45pm" in a text box? And how would I store the variable, as DateTime or TimeSpan?

This is my code:

  public partial class CreateMeetingWindow : Window {
        public string MeetingTYpe { get; set; }
        public string MeetingCode {get; set;}
        public DateTime MeetingDate { get; set; }
        public TimeSpan MeetingTime { get; set; }
        public bool Cancelled {get; set;}

        public CreateMeetingWindow(Window parent) {
                       InitializeComponent();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e) {
            MeetingCode = cbxMeetingType.SelectedValue.ToString ();
            MeetingCode = txtMeetingCode.Text;
            MeetingDate = DateTime.Parse(datePicker.SelectedDate.ToString ());
            Cancelled = false;
            this.Hide ();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e) {
            Cancelled = true;
            this.Hide();
        }
    }

So what I'm concerned about is the variable MeetingTime for example if the user enters it as "12:45pm" in the textbox

Upvotes: 0

Views: 187

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241525

.NET currently doesn't have a built-in type for time-of-day data. Your choices are:

  • Use a TimeSpan, though this is primarily designed for elapsed-time values, so it does not support AM/PM designators.

  • Use a DateTime, with an arbitrary date - being careful not to use the date part anywhere.

  • Use the LocalTime type from Noda Time, a third-party library. A LocalTime is a true time-of-day type.

Also, I'm not sure why you have:

MeetingDate = DateTime.Parse(datePicker.SelectedDate.ToString());

Instead of just:

MeetingDate = datePicker.SelectedDate;

If you want to combine them both, consider:

DateTime meetingDate = datePicker.SelectedDate;
DateTime meetingTime = DateTime.Parse(txtMeetingTime);
DateTime meetingDateTime = meetingDate.Date + meetingTime.TimeOfDay;  

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98750

Since MeetingTime is a TimeSpan (which is the right type in your case), you can't parse a string that contains ante meridiem or post meridiem designators to TimeSpan.

These designators are for DateTime type. TimeSpan is a time invertal. I would be meaningless when you try say something like; 12 hours and 45 minutes time invertal after noon. Doesn't make sense, right?

var s = "12:45";
var MeetingTime = TimeSpan.Parse(s);

Either you should prevent to typing designators in your textbox forcing entering to format as hh:mm or you should use some dropdownlists for entering hours, minutes and second values and combine them in the code behind.

Upvotes: 0

Related Questions