Reputation: 65
I'm pretty new to coding so sorry if my question has an obvious answer but I didn't find anything like that via the search.
I'm currently trying to make a time tracker database by using Windows Forms in C#.
My oroblem is the GUI has two DateTimePicker
: one displays the hours (dateTimePicker1
) which you can choose, and the other one displays the minutes (dateTimePicker2
) you can choose.
Both of them are starting with the current time when the form is loading.
I'm now trying to combine those two so that I get a string which gives me both hours and minutes with the chosen time.
If someone could help me here I'd be really glad because I'm currently out of ideas....
Upvotes: 2
Views: 1177
Reputation: 186793
Are you looking for this?
// myDatePicker displays date
DateTime day = myDatePicker.Value.Date;
// myTimePicker displays time
var timeOffset = myTimePicker.Value.TimeOfDay;
// combined value (day and time)
DateTime result = day + timeOffset;
In case you have three DatePickers (date, hour and minutes):
// myDatePicker displays date
DateTime day = myDatePicker.Value.Date;
DateTime result = day
.AddHours(myHourPicker.Value.Hour)
.AddMinutes(myMinutePicker.Value.Minute);
To display in required format use formatting:
// Hours and minutes
String text = result.ToString("hh:mm");
Upvotes: 2
Reputation: 411
Do you mean like this?
// take hour from first datetimepicker
DateTime hour = dateTimePicker1.Value.Hour;
// take minute from second datetimepicker
DateTime minute = dateTimePicker2.Value.Minute;
// combine hour and minute into an object
DateTime hourAndMinute = hour + minute;
// convert the combined DateTime into string
hourAndMinute.ToString("hh:mm");
If you want to convert it to string with different format you can check it here http://www.dotnetperls.com/datetime-format
If you actually need to represent length of time you should use this one http://www.dotnetperls.com/timespan
Mark as an answer if it help you :)
Upvotes: 3