WXforum.net

Weather Software => Cumulus => Topic started by: piconut on March 29, 2023, 05:59:43 PM

Title: javascript to convert 24 hour sunrise/sunset webtags to 12 hour (AM/PM)
Post by: piconut on March 29, 2023, 05:59:43 PM
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. 
Title: Re: javascript to convert 24 hour sunrise/sunset webtags to 12 hour (AM/PM)
Post by: mcrossley on March 30, 2023, 10:31:50 AM
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.
Title: Re: javascript to convert 24 hour sunrise/sunset webtags to 12 hour (AM/PM)
Post by: Stetson1 on March 31, 2023, 06:42:09 PM
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;
}
Title: Re: javascript to convert 24 hour sunrise/sunset webtags to 12 hour (AM/PM)
Post by: piconut on April 03, 2023, 05:23:59 PM
Thanks mcrossley and Stetson1 for your help on this.  I had originally searched and found the Cumulus list of webtags wiki page (https://www.cumuluswiki.org/a/Full_list_of_Webtags) but didn't know that some of them could have modifiers (https://www.cumuluswiki.org/a/Webtags/Parameters#Multiple_Output_Format_Modifier_parameters_for_times_and_dates).  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