From 05711b46364a8f5a53a5370e70d44a8537c1e100 Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Fri, 22 Oct 2021 18:46:58 +0200 Subject: [PATCH] Catch error if input_datetime state is incorrect (#10237) --- src/common/entity/compute_state_display.ts | 28 ++++++++++++---------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/common/entity/compute_state_display.ts b/src/common/entity/compute_state_display.ts index fddce09d82..fd99a022da 100644 --- a/src/common/entity/compute_state_display.ts +++ b/src/common/entity/compute_state_display.ts @@ -39,7 +39,7 @@ export const computeStateDisplay = ( const domain = computeStateDomain(stateObj); if (domain === "input_datetime") { - if (state) { + if (state !== undefined) { // If trying to display an explicit state, need to parse the explict state to `Date` then format. // Attributes aren't available, we have to use `state`. try { @@ -63,7 +63,7 @@ export const computeStateDisplay = ( } } return state; - } catch { + } catch (_e) { // Formatting methods may throw error if date parsing doesn't go well, // just return the state string in that case. return state; @@ -71,7 +71,17 @@ export const computeStateDisplay = ( } else { // If not trying to display an explicit state, create `Date` object from `stateObj`'s attributes then format. let date: Date; - if (!stateObj.attributes.has_time) { + if (stateObj.attributes.has_date && stateObj.attributes.has_time) { + date = new Date( + stateObj.attributes.year, + stateObj.attributes.month - 1, + stateObj.attributes.day, + stateObj.attributes.hour, + stateObj.attributes.minute + ); + return formatDateTime(date, locale); + } + if (stateObj.attributes.has_date) { date = new Date( stateObj.attributes.year, stateObj.attributes.month - 1, @@ -79,20 +89,12 @@ export const computeStateDisplay = ( ); return formatDate(date, locale); } - if (!stateObj.attributes.has_date) { + if (stateObj.attributes.has_time) { date = new Date(); date.setHours(stateObj.attributes.hour, stateObj.attributes.minute); return formatTime(date, locale); } - - date = new Date( - stateObj.attributes.year, - stateObj.attributes.month - 1, - stateObj.attributes.day, - stateObj.attributes.hour, - stateObj.attributes.minute - ); - return formatDateTime(date, locale); + return stateObj.state; } }