Thursday, July 22, 2010

Fun with Javascript Dates

I'm going to start a series on Javascript. I'm gonna post some cool and useful solutions that are not currently available on the internet (as far as I know).

Let's start small. Here is a function that will truncate the Time component from a date object. This can be useful when doing date comparisons, inadvertent bugs are introduced because of the time component.


<script type="text/javascript">
function removeTimeFromDate(inDate){ //i.e. set date to Midnight
return new Date(Date.parse(inDate.toDateString()));
}
//Test it out:
var now = new Date();
alert(now);
alert(removeTimeFromDate(now));
//Results:
//Thu Jul 22 2010 23:37:50 GMT-0400 (Eastern Daylight Time)
//Thu Jul 22 2010 00:00:00 GMT-0400 (Eastern Daylight Time)
</script>


Pretty simple, once you see it, yet most people write a ton of code to achieve this functionality. Another way is to return a new Date(inDate.getFullYear(), inDate.getMonth(), inDate.getDate())

You can add this functionality to the Date object itself, thereby extending it. I will show you how to do this in the next post.

1 comment:

JavaScript Media Player said...

very cool & good js tip, thank you very much for sharing.