Reputation: 1195
I am using the following javascript code that spits out a date in the format of mmddyy. Is there a way to add the results to a URL link, so that it spits out:
<a href="http://test.com/mmddyy.html">test
</a>
JS code I am using is
<script type="text/javascript">
function formatDate(d) {
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
year = year.toString().substr(2, 2);
month = month + 1;
month = month + "";
if (month.length == 1) {
month = "0" + month;
}
day = day + "";
if (day.length == 1) {
day = "0" + day;
}
return month + day + year;
}
var d = new Date();
document.write(formatDate(d));
</script>
Thanks for any help.
Upvotes: 1
Views: 116
Reputation: 66304
Create a HTMLAnchorElement
function pad2(x) { // pad/truncate number to 2 digits
return ('00' + x).slice(-2);
}
function formatDate(d) { // format your date output
return pad2(d.getMonth() + 1)
+ pad2(d.getDate())
+ pad2(d.getFullYear());
}
function generateLink(url, text) { // create an <a>
var a = document.createElement('a');
a.setAttribute('href', url);
a.appendChild(document.createTextNode(text));
return a;
}
var a = generateLink(
'http://test.com/' + formatDate(new Date) + '.html',
'test'
); // HTMLElement <a href="http://test.com/071613.html">test</a>
Now you can append this node as desired, e.g. if you wanted to convert back to String.
new XMLSerializer().serializeToString(a);
Or append to <body>
document.body.appendChild(a);
Upvotes: 1
Reputation: 964
There are multiple ways to do this.
First, you should avoid using document.write
. Instead, the simplest way is to create a div to write to, like this:
<body>
<div id="myDiv"></div>
</body>
You can then add a link to it like this
document.getElementById('myDiv').innerHTML = '<a href="http://test.com/'+formatDate(d)+'.html">test</a>';
If there is an existing link, for example <a href="#" id="myLink">test</a>
, you can set the url like this
document.getElementById('myLink').href = 'http://test.com/'+formatDate(d)+'.html';
Upvotes: 0
Reputation: 9040
You can concat the string with the link URL:
var link = "http://www.test.com/"+formatDate(d)+".html";
Then alter the <a>
tag accordingly:
document.getElementById('link_id').href = link;
Upvotes: 0