1

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...

henryaaron
  • 6,042
  • 20
  • 61
  • 80
  • You can't find out the server's day of the week from JavaScript, only the client's day of the week (and even then, only what the user has set their system date to be). As far as JavaScript date manipulation goes, read [the doco at MDN](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) - all the date methods are listed with some examples. Also, if your requirement is MM/DD/YYYY format why are your example dates in M/D/YYYY format? – nnnnnn Jan 01 '12 at 07:35

3 Answers3

3

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;
}
Luis Perez
  • 27,650
  • 10
  • 79
  • 80
  • I'm not trying to just add 6 days to the date, I want to add 6 days on Monday only, 5 days on Tuesday, 4 days pon Wednesday, all the way till 0 days on Sunday... – henryaaron Jan 01 '12 at 09:14
  • Hey @user1090389 that's what it does actually. getDay() actually returns the weekday not the actual day of the month, getDate() returns the day of the month. I should have explained that along with my answer, I'll update my answer to do that now. – Luis Perez Jan 01 '12 at 16:41
  • How do I implement this into my document? – henryaaron Jan 01 '12 at 20:01
  • Hey @user1090389, I added the additional details you requested. – Luis Perez Jan 01 '12 at 20:22
  • Awesome it's almost perfect, it's just I don't want the week to end on Saturday, I want it to end on Sunday, how can I do that? – henryaaron Jan 01 '12 at 20:29
  • Hey @user1090389, I modified the code in 2 places to account for the week starting on Monday. I broke out today.getDay() into a separate line to store the value in weekDay and I added some code to the bottom of the answer to show how to adjust. If this code accomplishes what you wanted please make sure to accept it as an answer, thanks. – Luis Perez Jan 01 '12 at 20:44
  • Of course... but I feel dumb because I don't even where to put that third code... JavaScript confuses me – henryaaron Jan 01 '12 at 20:49
  • Where should I put the `weekDay -= 1; if(weekDay < 0) { weekDay += 7; }` – henryaaron Jan 01 '12 at 21:16
  • Hey @user1090389, I updated the answer to include the code that adjusts for Monday vs. Sunday. I included it in the right place as commented out code, you would just need to uncomment it. – Luis Perez Jan 01 '12 at 21:19
  • Maybe you'd be able to help me with this: http://stackoverflow.com/q/8695663/1090389 – henryaaron Jan 01 '12 at 21:27
0

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!

Jim Davis
  • 1,230
  • 6
  • 11
  • I've added information about how I would grab the day as an integer using your rules to the original answer. Hope it helps. – Jim Davis Jan 01 '12 at 19:39
0
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()
)
  • That only works Sunday through Wednesday. On Thursday and Friday it returns Saturday the 14th. On Saturday it returns Saturday the 7th... – henryaaron Jan 01 '12 at 20:00