Best way to get date and time inputs from user and save as a datetime variable
Mostrar comentarios más antiguos
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');
Respuesta aceptada
Más respuestas (1)
Kevin Holly
el 27 de Abr. de 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 comentarios
Rich006
el 27 de Abr. de 2023
Kevin Holly
el 27 de Abr. de 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.
Rich006
el 27 de Abr. de 2023
Categorías
Más información sobre Startup and Shutdown en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!