Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - How to insert today's date into a URL?

I have a url that change every day based on today's date, for example:

http://www.newspaper.com/edition/20141227.html

where 20141227 is in the format YYYYMMDD.

Can I include the date using JavaScript? If possible, how would I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think following steps will help you to achieve the functionality your are looking for

1.Convert the today's date or any date to intended format that is "YYYYMMDD" in your case.

2.Then append it to your URL.

Please look into code snippet for details. Note you just need to hover over URL to know what it is pointing to.

Date.prototype.toMyString = function () {
   //If month/day is single digit value add perfix as 0
    function AddZero(obj) {
          obj = obj + '';
          if (obj.length == 1)
              obj = "0" + obj
          return obj;
    }

    var output = "";
    output += this.getFullYear();
    output += AddZero(this.getMonth()+1);
    output += AddZero(this.getDate());

    return output; 
}

var d = new Date();

var link = document.getElementById("link");

link.setAttribute("href","/yourchoiceofURL?t="+d.toMyString());
<ul>
    <li><a id="link" href="#">Any URL</a></li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...