Monday, July 26, 2010

JS tips - I

Level: Moderate

String to integer conversion (Caution with parseInt):

Remember to always include the base with parseInt, otherwise you can introduce hard to find bugs. If the string has a leading zero, it is evaluated with base 8 (Octal). Therefore "015" will return 13. The correct way is parseInt('015', 10);

A neat way is to achieve the same is to simply put a plus sign in front of the string variable. That forces a type conversion to decimal:
var s="015"
var i= +s + 2;
console.log(typeof i);
console.log(i);
//results in:
// number
// 17

Trim() for strings:

You can extend the String object to include trim, ltrim and rtrim with a little regex to strip off the surrounding white spaces.

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
String.prototype.ltrim = function() {
return this.replace(/^\s+/, '');
};
String.prototype.rtrim = function() {
return this.replace(/\s+$/, '');
};


Now you can use trim any string variables, input field values, or even string literals. For example:

<input id="firstname" onchange="value=value.trim()" />

Sunday, July 25, 2010

Fun with Javascript Dates III

Level:Moderate

Javascript Date objects can be created with the following parameters:
new Date(year, month, date, hours, minutes, seconds, milliseconds)
If you only specify the first two parameters, all others are assumed to be zero.
This date instantiator has a very interesting feature. The parameters for month, date(i.e. monthday), hours etc do not have the standard upper and lower bound. They can be any integer. For example monthday can be negative or greater than 31.

var d = new Date(2010,0,1) // will yield 1st Jan 2010
var d = new Date(2010,0,-2) // 29 Dec 29 2009 (back 3 days)
var d = new Date(2010,0,-2, 100) //1st Jan 2010, 4am (minus 3 days plus 100 hours)

This was a very cool design decision, because now it becomes very easy to perform date addition.

1. Add/Subtract days and months etc to a date

var d = new Date(); //today's date
var d2=new Date(d.getFullYear()+3,d.getMonth()+4,d.getDate()+5)
//d2 is set to 3 years, 4 months and 5 days in the future

Better still, we can extend the Date Object’s behavior and add this functionality.

Date.prototype.addDays = function(days) {
return new Date(this.getFullYear(),this.getMonth(),this.getDate()+(+days))
}
//See my ParseInt blog if you think the (+days) is odd looking
//Usage:
//var now = new Date();
//var Yesterday = now.addDays(-1);
//alert(Yesterday);

I’ll leave it up to you to implement addMonths() and addYears(), Hours, Minutes, Seconds.

2. Day of the Year: (Julian Day)

Date.prototype.getDOY = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
}

3. Week of Year

Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

4. Fiscal Year if your new year starts on October 1st of the previous year.
We can use the addDays() prototype function we just created!

Date.prototype.getFiscalYear = function() {
return this.addDays(92).getFullYear();
}

Datejs library on googlecode, has amazing functionality added on to the Date object. Many other major frameworks have similar libraries.

Friday, July 23, 2010

Fun with Javascript Dates - II

1. Javascript Date object has many differences from .Net DateTime type. Some of the prominent differences are:
  • Month is zero based integer (0 to 11) - this can be a source of many a bug.
  • Weekday (getDay) returns 0-6 for Sunday-Saturday

    To get descriptive weekday, you can extend the date object's functionality like so:

    Date.prototype.getDayShort=function(){
    return ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][this.getDay()];
    }
    //Test it:
    alert((new Date(2010,1,1)).getDayShort())

    This will popup "Mon". Some of you are looking up the calendar and thinking "shouldn't 1st Jan be a Friday". No Siree, the date is 1st Feb -- did you already forget my month's tip above? I will leave it up to you to implement a getLongDay() function.

    The cool trick above is declare a lookup array on the fly. It saves a line of code, and an additional variable, and can be useful for small, one-time-use lookups. You can use the same trick with JSON objects. For example:

    alert({black:"#000000", blue:"0000ff", red:"#ff0000"}["blue"]);

    2. One biggie is the Y2K bug. Javascript and .Net have methods to create date objects from numbers. Javascript's Date(yy,mm,dd) constructor will treat all 2 digit year to be 19th century, while .Net has DateTime.Parse method which assumes years "0" to "29) to be 20th century. To mimic .Net's behavior check for date under 30, and add 2000, as shown below:

    for(var i=0;i<102;i++)
    console.log(new Date(i<30?i+2000:i,1,1));
  • 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.