Tuesday, 21 October 2014

Some JavaScript Date Formatting Tips


1. Date formatting from date string

    strDate =  "2012-08-02T07:00:00+0000"; // For Eg

    function formatDate(strDate){
        var monthNames = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec");
        var date = new Date(strDate);
        return monthNames[date.getMonth()]+ ' '+ date.getDate();
    }


 2. Date formatting from time stamp

function timeStampToDate(timeStamp){
    var date = new Date(timeStamp * 1000);
    return (date.getMonth() +1 )+ '/'+ date.getDate()+'/'+ date.getFullYear();
}

3. Week start or week end for a day

  function getWeekDay(date, day){
    var targetDay;
    var currentDay = new Date(endDate);
    if(day == 'next'){
        // add 6 days
        targetDay = new Date(currentDay.getTime() + (86400000 * 6 ));
        // 24*60*60*1000 = 86400000 (day in milliseconds)
    }else{ // previous
        // subtract 6 days
        targetDay = new Date(currentDay.getTime() - (86400000 * 6 ));
        // 24*60*60*1000 = 86400000 (day in milliseconds)
    }
    return targetDay
   }

0 comments:

Post a Comment