Author Topic: javascript to convert 24 hour sunrise/sunset webtags to 12 hour (AM/PM)  (Read 894 times)

0 Members and 1 Guest are viewing this topic.

Offline piconut

  • Juggler Extraordinaire
  • Forecaster
  • *****
  • Posts: 365
    • South Austin Weather
Greetings,


I copied some HTML and javascript code from the internet to create a webpage that shows current weather conditions on an old Android tablet that I have hanging on the wall.  I'm using the webtags feature of CumulusMX to pull data from the weather station and input it into the webpage along with some javascript that is used to "color code" the temperature data according to the current temperature.  I tried to add the #sunrise and #sunset webtags but the webtags are in 24 hour format.  Does anyone know of some javascript to convert the 24 hour time into 12 hour (AM, PM)?   I'm assuming that I need javascript because that is what the other scripts I copied are using.


Currently, the #sunrise webtag gives me 07:25 and the #sunset webtag gives me 19:49.  I would like to show these as 7:25 AM (dropping the preceding zero and adding AM) and 7:49 PM (converting the 24 hour time to 12 hour and adding the PM). 


Any help here is certainly appreciated. 
  • Davis Vantage Pro 2 Plus
  • Virtual VP
  • Virtual Weather Station V15.00
  • Cumulus
  • Cumulus MX
  • Image Salsa
  • IP TimeLapse

Offline mcrossley

  • Forecaster
  • *****
  • Posts: 1132
    • Wilmslow Astro
You just need to apply a time format to the web tag, if you want 12 hr with am/pm and no leading zero on the hours use:

format="h:mm tt"

or if you are using the US locale then just:

format="%t"

<#sunrise format="???">

The tags and modifiers are all documented in the Cumulus Wiki.
Mark

Offline Stetson1

  • Cordera Weather
  • Forecaster
  • *****
  • Posts: 364
    • Cordera Weather
Pretty simple Javascript function, just need to sort out where to place it in your code:

function convertTime(time) {
  let hours = parseInt(time.substring(0, 2));
  let minutes = time.substring(3, 5);
  let ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12;
  return hours + ':' + minutes + ' ' + ampm;
}

Offline piconut

  • Juggler Extraordinaire
  • Forecaster
  • *****
  • Posts: 365
    • South Austin Weather
Thanks mcrossley and Stetson1 for your help on this.  I had originally searched and found the Cumulus list of webtags wiki page but didn't know that some of them could have modifiers.  I was able to use the modifiers to get the 12 hour time format like this:  <#sunset format="h:mm tt">
Which gave me this: Sunset at 8:24 PM

« Last Edit: June 10, 2023, 02:37:46 PM by piconut »
  • Davis Vantage Pro 2 Plus
  • Virtual VP
  • Virtual Weather Station V15.00
  • Cumulus
  • Cumulus MX
  • Image Salsa
  • IP TimeLapse

 

anything