Best way to get date and time inputs from user and save as a datetime variable
34 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Stephen23
le 27 Avr 2023
Modifié(e) : Stephen23
le 29 Avr 2023
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 commentaires
Plus de réponses (1)
Kevin Holly
le 27 Avr 2023
% 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 commentaires
Kevin Holly
le 27 Avr 2023
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.
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!