facebook style post dates

A very quick bodge function for returning a nice post time.
Returns stuff like “2 seconds ago”,”23 minutes”, “about an hour”, “3 hours ago”,”yesterday at 3:00pm”,”wed at 3:00pm”, “Nov 2 at 3:00pm”

Haven’t tested it much so might want a tweak and I haven’t added year as I don’t really need it. Leave the second parameter out to use the system date as current.

trace( postTime( new Date( "18:07:12 2009/11/14" ) ) );

function postTime( dateToCheck:Date, currentDate:Date = null ):String
{
    if( currentDate == null ){
        currentDate = new Date( );
    }
    var day_name:Array = ["Sun","Mon","Tues","Wed","Thurs","Fri","Sat"];
    var month_name:Array = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"];
    var theTime:String;
    var day_dif:int;
    var seconds:int = ( currentDate.valueOf() - dateToCheck.valueOf() ) / 1000;
    if( seconds < 60 ){
        return Math.max( 2, seconds ) + " seconds ago ";
    }else if( seconds < 3540 ){
        return Math.round(seconds/60) + " minute"+ ( seconds<120?"":"s" ) + " ago ";
    }else if( seconds < 6500 ){
        return "About an hour ago";
    }else if( seconds < 86400 && ( currentDate.day == dateToCheck.day ) ){
        return Math.round(seconds/3600) + " hours ago";
    }else{
        theTime = ( dateToCheck.hours % 12 ) + ":" + dateToCheck.minutes + (( dateToCheck.hours>12 )?"pm":"am");
        dateToCheck.hours = currentDate.hours;
        day_dif = Math.round( ( currentDate.valueOf() - dateToCheck.valueOf() ) / 86400000 );
        if( day_dif == 1 ){
            return "Yesterday at " + theTime;
        }else if( day_dif < 7 ){
            return day_name[ dateToCheck.day ] + " at " + theTime;
        }else{
            return month_name[ dateToCheck.month ] + " " + dateToCheck.date + " at " + theTime;
        }
    }
}
This entry was posted in flash. Bookmark the permalink.

Comments are closed.