How do I improve the script below?
I would like the date to be written in mmdddyyyy
like 11/12/2017
, but I can't help but write Nov12
. Can you fix it?
function getWeatherData(){
// Seat Settings
vars = SpreadsheetApp.getActiveSpreadsheet();
varsh=ss.getSheetByName("Sheet2");
var lr = sh.getLastRow();
//
var url="https://weather.com/weather/monthly/l/USCA9009:1:US";
var response=UrlFetchApp.fetch(url, {muteHttpException:true});
if(response.getResponseCode()!=200){
return;
}
varbody=response.getContentText();
// date
varregExp=/<th class="col-labels record-date"><strong>>span>.*?<\/span><\/strong><\/th>/g;
values = body.match(regExp);
vardate=elems[0].split(">")[3].split("<")[0];
// maximum temperature
varregExp2 = /<h3>Record High<\/h3><span class="">.*?<\/sup>/ // Maximum Temperature
values2 = body.match(regExp2);
var high=elems2[0].split(">")[3].slice(0,-4);
// minimum temperature
varregExp3=/<h3>Record Low<\/h3><span class="">.*?<\/sup>//Minimum Temperature
values3 = body.match(regExp3);
var low=elems3[0].split(">")[3].slice(0,-4);
// transcription
sh.getRange(lr+1,1,1,3).setValues([date, high, low]]);
}
If you visit https://weather.com/weather/monthly/l/USCA9009:1:US", the only HTML source that matches the regular expression is "Nov13" (as of November 14, 2017)
Only 13 can use yyyymmdd strings such as 11/13/2017 in this string.
Month 11 should be derived from the information that Nov stands for November in English, and year 2017 should be derived from the date and time of the U.S. when accessing the page.
If you want to modify the code in the question,
Month
·Prepare the association table (associative array) for the abbreviation of the month and the month (number) in English.
varmonthHash={Jan:01, Feb:02, ..., Dec:12}
"·The regular expression contains a date (month/day) like ""Nov13"", so you can get the month (number) by taking out the first three characters and using the correspondence table above (substring(0,2) can take out the first to third characters).
varmm=monthHash(em.substring(0,3)))
Day
·Take out the 5th and 6th characters of elem and you'll get the day.
vardd=elem.substring(4,6)
Year
·You can get the current date and take your age out of it.
var now=new Date();
varyyyy=now.getFullYear();
So far, mm, dd, yyyy have 11, 13, and 2017 respectively, so all you have to do is display whatever you want.
Please refer to the code fragment above and try it.
© 2024 OneMinuteCode. All rights reserved.