Get XML file, based on current date
I am very new to parsing XML data with javascript, so please excuse me if my question is a bit simple.
I am parsing data from an XMl file with javascript using a standard xmlHTTPRequest. The format of th开发者_如何转开发e URL that I am pulling the XML data from is something like: "http://example.com/abcyymmdd-data.xml". The (yymmdd) portion of the url represents the date and the files are updated daily. I would like to insert a javascript code in the url in place of yymmdd so that a new XML file is parsed each day. How might I achieve this?
Thanks, Carlos
First, to get today's date, use:
var today = new Date;
To get the components, use:
var date = today.getDate();
var month = today.getMonth() + 1; // caveat, starts at 0
var year = today.getFullYear(); // 4 numbers (e.g. 2011)
Now, you need it in the format yymmdd
. So you need to remove the two first numbers from year, and prepend a 0
to date and month, if necessary.
function zeropad(number) {
var str = number.toString(); // number to string
return str.length === 1 // if length is 1
? '0' + str // prepend a 0
: str; // otherwise return string without modification
}
And then:
var formatted = year.toString().substring(2) // only the string from the first two numbers and on
+ zeropad(month) // month with 0 prepended
+ zeropad(date); // date with 0 prepended
Then, in your XHR, use:
xhr.open("GET", "http://example.com/abc" + formatted + "-data.xml", true);
You can retrieve the current date in yymmdd
format like:
var d = new Date();
var date_string =
d.getFullYear().toString().substring(2) +
(d.getMonth () < 9 ? "0" : "") + (d.getMonth() + 1) +
(d.getDate() < 10 ? "0" : "") + d.getDate();
Example at JS Fiddle.
精彩评论