Weather Software > Cumulus

javascript to convert 24 hour sunrise/sunset webtags to 12 hour (AM/PM)



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. 

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:


<#sunrise format="???">

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

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;

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


[0] Message Index

Go to full version