Best way to get date and time inputs from user and save as a datetime variable
40 次查看(过去 30 天)
显示 更早的评论
My App Designer app allows the user to input a date and time range (start date, start time, end date, end time). I have 2 date pickers and two edit fields for the times (strings 'hhmm'). I save the 4 inputs as fields in a struct s. What is the cleanest way to incorporate the time inputs into the date variables? Or is there a better approach? The below works, but I feel there should be a slicker way.
% construct the data subset timerange
startDateTime = datetime(s.StartDate) + ...
hours(str2double(s.StartTime(1:2))) + ...
minutes(str2double(s.StartTime(3:4)));
endDateTime = datetime(s.EndDate) + ...
hours(str2double(s.EndTime(1:2))) + ...
minutes(str2double(s.EndTime(3:4)));
subsetPeriod = timerange(startDateTime,endDateTime,'closed');
0 个评论
采纳的回答
Stephen23
2023-4-27
编辑:Stephen23
2023-4-29
No conversion back-and-forth is required: your approach of adding a DATETIME and DURATION object is the correct one. Sadly the DURATION creation has a very limited set of accepted formats, otherwise this really would be a trivial task :( So until TMW makes DURATION more flexible, we need workarounds. Here are three approaches:
HM = '2359'; % 'hhmm'
DT = datetime(2023,04,27)
%Z0 = DT+duration(HM, 'InputFormat','hhmm') % what we want, but TMW won't allow.
Z1 = DT+duration([sscanf(HM,'%2d',[1,2]),0])
Z2 = DT+duration(regexprep(HM,'(..)(..)','$1:$2'), 'InputFormat','hh:mm')
Z3 = DT+duration([HM(1:2),':',HM(3:4)], 'InputFormat','hh:mm')
Checking:
isequal(Z1,Z2,Z3)
0 个评论
更多回答(1 个)
Kevin Holly
2023-4-27
% construct the data subset timerange
startDateTime = datetime(s.StartDate + " " + s.StartTime, 'InputFormat', 'yyyy-MM-dd HHmm');
endDateTime = datetime(s.EndDate + " " + s.EndTime, 'InputFormat', 'yyyy-MM-dd HHmm');
subsetPeriod = timerange(startDateTime, endDateTime, 'closed');
3 个评论
Kevin Holly
2023-4-27
In that case,
% convert datetime values to strings with format 'yyyy-MM-dd'
startDateStr = datestr(s.StartDate, 'yyyy-MM-dd');
endDateStr = datestr(s.EndDate, 'yyyy-MM-dd');
% construct the data subset timerange
startDateTime = datetime(startDateStr + " " + s.StartTime, 'InputFormat', 'yyyy-MM-dd HHmm');
endDateTime = datetime(endDateStr + " " + s.EndTime, 'InputFormat', 'yyyy-MM-dd HHmm');
subsetPeriod = timerange(startDateTime, endDateTime, 'closed');
Not sure if it better than what you have.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!