custom-cards / button-card

❇️ Lovelace button-card for home assistant
MIT License
1.97k stars 242 forks source link

Problem with relative_time in cards. Help appreciated #653

Closed krasatos closed 1 year ago

krasatos commented 1 year ago

How can i parse a state formatted as relative_time?

This works great and returns a date/time format: label: "[[[ return states['binary_sensor.movement_dn_lr_unified'].last_changed ]]]"

If i try to add the relative time (xx minutes ago) like this: label: "[[[ return relative_time(states['binary_sensor.movement_dn_lr_unified'].last_changed) ]]]"

I get the following error: ButtonCardJSTemplateError: ReferenceError: relative_time is not defined in 'return relative_time(states['binary_sensor.movement_dn_lr_unified'].last_changed)'

How can i achieve this? TiA

edit: I have done it with the following code for now, but isn't there a simpler solution?

label: >
  [[[
        var currentTimestamp = Math.floor(new Date().getTime() / 1000) 
        var lastTimestamp = Math.floor(new Date(states['binary_sensor.movement_dn_lr_unified'].last_changed).getTime() / 1000)
        var timeDiff = currentTimestamp - lastTimestamp
        if (timeDiff < 10)
          return 'Just now'
        else if (timeDiff < 60)
          return timeDiff + ' seconds ago'
        else if (timeDiff < 120)
          return ' 1 minute ago'
        else if (timeDiff < 60*60) 
          return Math.floor(timeDiff/60) + ' minutes ago'
        else if (timeDiff < 60*60*2) 
          return ' 1 Hour ago'
        else if (timeDiff < 60*60*24) 
          return Math.floor(timeDiff/60/60) + ' hours ago'
        else if (timeDiff < 60*60*24*2) 
          return ' Yesterday'
        else return Math.floor(timeDiff/60/60/24) +' days ago'

  ]]]
RomRider commented 1 year ago

Latest beta and future 4.0.0 supports this: [[[ return relativeTime(states['binary_sensor.movement_dn_lr_unified'].last_changed) ]]]

Closing in favor of #701