Does javascript have a simple get day of the year type function?
Hi, wondering if I can get an item by day of the year using javascript. Sort of like their getDay() type commands but for the year instead of the month.
Don't see anything, does anyone know of anything like this without doing
a lot of writing to create it? Thank you very much!
The Date() function in javascript returns the number of milliseconds since 1/1/1970. So you can calculate how many ms since the first of the year and then convert to days:
Code:
<script type="text/javascript">
var today = new Date();
var first = new Date(today.getFullYear(), 0, 1);
var theDay = Math.round(((today - first) / 1000 / 60 / 60 / 24) + .5, 0);
alert("Today is the " + theDay + (theDay == 1 ? "st" : (theDay == 2 ? "nd" : (theDay == 3 ? "rd" : "th"))) + " day of the year");
</script>
No I was wondering how to add your idea to what I gave you, to make mine appear by day of the year instead. Right now it works just fine doing day of the week or month, I was trying to make it do day of the year instead. Thanks though.
And Gil forgot about daylight saving time. His code contains a subtle bug that Rianna might well have not noticed.
Let me see what I can do:
Code:
function dayofyear(d) { // d is a Date object
var yn = d.getFullYear();
var mn = d.getMonth();
var dn = d.getDate();
var d1 = new Date(yn,0,1,12,0,0); // noon on Jan. 1
var d2 = new Date(yn,mn,dn,12,0,0); // noon on input date
var ddiff = Math.round((d2-d1)/864e5);
return ddiff+1; }
Please bear with me Juu, I have only been doing js for 6 months so I just want to make sure I understand it. The two lines you just gave me, is that all I need, or do I need to add that somehow to the rest you gave me. Thanks, Rianna
JavaScript allows you to create your own functions. I strongly suggest you read up on this.
The first piece of code I gave you was a function I wrote. It contains code which tells your JavaScript interpreter how to calculate the day of the year for a date.
The second piece of code relies on the first piece of code, and is an example showing how the first piece of code works.
Thanks Juu, luckily I know about functions but there was so much code in the first one
I didn't know if you were sending me ideas, or the real deal. Sounds like the real deal. Thank you very, very, much. I'll see if I can do anything with it. Appreciated, Rianna
That is just too cool! Thank you very much, this is what I have been looking for. I'll let you now how it goes. Most of us felines don't pick this stuff up as easily as you fellas seem to, but I guess we're working on it. Thanks again!
Bookmarks