简体   繁体   中英

Taking a DateTime value and only accepting time and vice versa

I'm currently developing an application to function as a todo - list and i was wondering how do i accept a Value from a date time box, but only use the value of the date, or the value of the time. I'm currently doing it like this.

DateTime ted = appointmentDateTimeDate.Value; //The date
DateTime at = appointmentDateTimeTime.Value;  //The time

should i be doing this another way?

Use DateTime.Date property for date, and DateTime.TimeOfDay for time:

DateTime ted = appointmentDateTimeDate.Date; //The date
TimeSpan at = appointmentDateTimeTime.TimeOfDay;  //The time

The BCL doesn't really separate dates and times nicely.

If you're happy to take a new external dependency, I'd like to plug my Noda Time library, which will let you separate things out clearly into LocalDate and LocalTime . To perform the conversion from a date/time picker you'd probably use:

var dateAndTime = LocalDateTime.FromDateTime(appointmentDateTimeDate.Value);
LocalDate date = dateAndTime.LocalDate;
LocalTime time = dateAndTime.LocalTime;

A DateTime value ALWAYS contains both the date and the time, whether you use both or not.

You can use the . Date property of a DateTime to get "just the date". it will still have a time value, but the time value will be midnight. You can also use the . TimeOfDay property to get the time portion, which will be a TimeSpan indicating the number of ticks since midnight.

I'm taking a leap here and assuming you're trying to set the date with one control an d the time with another in the UI. Here's a sample of some code we use to do this using an Ajax CalendarExtender attached to a textbox and a custom TimePicker control .

    DateTime dt;
    try
    {
        dt = Convert.ToDateTime(txtViewDate.Text).AddHours(txtViewTime.Hour).AddMinutes(txtViewTime.Minute);
        if (txtViewTime.AmPm == MKB.TimePicker.TimeSelector.AmPmSpec.PM)
        {
            dt = dt.AddHours(12);
        }
        System.Diagnostics.Debug.WriteLine(dt.ToString());

    }
    catch (Exception)
    {
        // abort processing
        return;
    }  

Like others pointed out a DateTime always has both a date and a time component. So although it's possible to save both independently using two DateTime , in most cases it's recommendable to save both together in a single DateTime instance.

You should see if you really need both values separated or if your application could combine both in one property, which will make things easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM