Question

I don't really know too much about core JavaScript, just a dot of jQuery. But I know jQuery is not necessary for what I need here:

I want to use the getdate function to find out the server's day of the week. Then add a bunch of clauses like:

  • if its Monday add 6 to the date and return the date in MM/DD/YYYY form.
  • if its Tuesday add 5 to the date and return the date in MM/DD/YYYY form.
  • if its Wednesday add 4 to the date and return the date in MM/DD/YYYY form.

and so on until Sunday when it will add 0.

So lets say todays Monday, it will return 1/8/2012 And in real dates today's Sunday so it will really return 1/1/2012

Then I just want to call a document.write function to write the MM/DD/YYYY it returns into my HTML document.

Can anybody help me? I can clarify if you need me to...

Was it helpful?

Solution

getDay() returns the day of the week, Sunday = 0, Monday = 1, etc, etc.

So say today was Monday getDay() would return 1, which means daysToAdd would be 5.

Once we know how many days we want to add we can create a new date and add those days. We do this by getting today in milliseconds and then adding the number of days (daysToAdd) in milliseconds.

We convert days to milliseconds by multiplying by 24*60*60*1000 which is the number of milliseconds in a day.

I add 1 to the month because JavaScript returns 0 based month, but for display purposes we want to format it so that January for example is 1 not zero.

function getEndOfWeek() {
    var today = new Date();
    var weekDay = today.getDay();
    // if you want the week to start on Monday instead of Sunday uncomment the code below
    //weekDay -= 1;
    //if(weekDay < 0) {
    //    weekDay += 7;
    //}
    var daysToAdd = 6 - weekDay;
    var newDate = new Date(today.getTime() + daysToAdd *24*60*60*1000);
    var month = newDate.getMonth() + 1;
    var day = newDate.getDate();
    var year = newDate.getFullYear();
    var formatedDate = month + "/" + day + "/" + year;
    return formatedDate;
}

You could implement in your code like so, JavaScript:

$(function() {
    $("#TheDate").html(getEndOfWeek());
});

Your HTML would be something like this:

The week ends on <span id="TheDate"></span>.

You can find the jsFiddle here: jsFiddle

If you want to adjust the weekday so that you consider Monday the start of the week instead of Sunday you can do the following after you get the weekDay:

weekDay -= 1;
if(weekDay < 0) {
    weekDay += 7;
}

OTHER TIPS

var day = 1000*60*60*24
, nextSunday = new Date(+new Date() + day*(7-((0|(+new Date()/day)%7-3)||7)));

alert(
    (101+nextSunday.getMonth()).toString().substr(1) + '/' +
    (100+nextSunday.getDate()).toString().substr(1) + '/' +
    nextSunday.getFullYear()
)

As fas as adding dates in JavaScipt my "DateExtensions" library does this well enough, I think. You can get it here:

http://depressedpress.com/javascript-extensions/dp_dateextensions/

Once refenced you can call "add()" as a method for any valid date and pass it any of many date parts (second, minutes, days, hours, etc). So assuming "curDate" is a valid JavaScript date object you can add 5 days like this:

newDate = curDate.add(5, "days");

Using a negative value will subtract:

newDate = curDate.add(-5, "days");

Once you get the date you want you can the use the library's dateFormat() method to display it like so:

curDate.dateFormat("MM/DD/YYYY");

There's full documentation at the link.

Integer Values for Day of Week

As for getting the integer value you want, it's actually easier that it looks (and you don't need an "if" just some math). The getDay() method of date returns the day of week with Sunday as "0" and Saturday as "6". So the week, from Sunday, would normally be:

0,1,2,3,4,5,6

First, you want to reverse that scale. That's easily done via subtraction by taking 7 (to total number of members of the set) from the value. This gives you this scale:

-7,-6,-5,-4,-3,-2,-1

We're getting closer. You want the first value to be zero as well. The simplest way (I think) to do this is to get the modulus (remainder) of the value by the total number of members. All this basically does is make "-7" a zero and leave the rest alone giving us this:

0,-6,-5,-4,-3,-2,-1

Almost done. Finally you don't want negative numbers so you need to use the Math.abs() method to eliminate the sign (get the absolute value) leaving us with our desired result:

0,6,5,4,3,2,1

For all the talk the acutual code is pretty compact:

Math.abs((cnt-7)%7)

Wrapping this into the original example gives us:

newDate = curDate.add(Math.abs((curDate.getDay()-7)%7), "days");

Server Vs Client

However take nnnnnn's comment to heart: in JavaScript the getDate() function gets the current date/time of the machine that it's running on - in the case of a web page that's the client, not the server.

If you actually meant the client time them you're set and done. If you really need the server time however that's annoying-to-impossible. If you own the server then it's actually not to hard to set up a rule that includes the current server in a cookie withing each fufilled request (you could then use my cookie library, also at the site above, to access the information!)

It's messier but depending on the server you might also be able to create an old-school server-side include that adds a bit of JavaScript to each page (preferably as a marked replace in the header) that hard-codes the date as a global variable.

You might also create a web service that returns the current server time but the client-overhead for that is insane compared to the data being delivered.

If the server's NOT yours (and you can't get the owner to provide the above) then the only real potential option is to do a straight http call and examine the HTTP "Date" header. Again however the overhead on this is immense compared to the return but it's really the only way. Any system like this would have to be very flexible however as any particular server might not return the date header or might not return it correctly.

Even if it does work understand that you might still not be getting the "server" time - or at least not the server you want. In a tiered architecture, for example an application server might render then page and hand it to a web server to return - you'd be getting the web server time, not the app server. Any number of appliances might also rewrite the headers (for example it's common to use dedicated SSL appliances to offload all the encryption work - these often re-write the headers themselves).

Sorry to get overly technical - JavaScript is definately one area where there's unfortunately rarely a "simple question". ;^)

Good Luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top