Wednesday, August 5, 2009 0 comments

Java Script Date Object

Java script consist of a Date object which is kind of similar to the Java Date object where as it uses the time since the epoch but some utility method available in the Java language are not available in the JS Date object version. Some of the utility method which i cared to share are as follows;

getDate() - Get the day of month e.g 1-31
getMonth() - Gets the month of the year. Note that it starts with 0-11 So Jan is basically 0.
getFullYear() - Gets the current year as a four digit character

Also we can pass the date as a string literal to the date object as new Date("08/09/2007") which it will convert to the intended date time. It also consists of a toString method which is a bit too cryptic and should not be used when showing specific date objects. The above in-built methods should be used instead to show the user a properly formatted date.

How do you get teh number of days between two days;

This can be done as follows;

//Assuming that date 2 is after date 1
function(date1,date2){

return Math.round( (date2-date1)/(1000*60*60*24));

}
0 comments

Java Script Array Sorting


Java scripts have intrigued me!!!As so far as me going to the book store and selecting java script books to learn it the old fashioned "Off the shelf" way ;) ... So some of my posts from here onwards will contain a mix and match of java scirpt/java so any anti javascript ppl please dnt take it personally :D.... I never knew java script had array sorting like whats available for us java developers. Two ways this can be accomplished..

Method 1:

//Sorts values in descending order
function compare(val1,val2){
return val2-val1;
}

var myarray = new Array([1,3,7,10,32,45]);
myarray.sort(compare);

Thats about it to do sorting using arrays. Of course you could have just used myarray.sort() which would have used the default sorting mechanism and sorted the array in ascending order. You could debate here saying why do we need to define a new method just to get the sorting done. Bit too much code to do a single sorting function. Well look no further method 2 below shows how to do the same thing as above with just one line of code using the function literal capability of Javascript.

Behold Method 2!!!!!!! (Drum roll please)
Method 2:
myarray.sort(function(val1,val2){val2-val1});


Thats about it for now. But more to come very soon guys. So stay on the look out for all those Java script newbies like myself :).

Cheers
 
;