Friday, April 20, 2012

JavaScript and Date Time formatting

Scenario: Working with SP client object model , I was getting formatted date string. Not very good for display purpose.
Solution: I asked our in house JavaScript expert sanjay and got a kick start , here's a little bit modified version of that outputting UTC date time.
Code:

//function for the getting the formatted date and time 
// current output April 20, 2012 7:04 PM
function formattedUTCDateTime(d) {

    // code for the year
    var m_names = new Array("January", "February", "March",
    "April", "May", "June", "July", "August", "September",
    "October", "November", "December");

//    var d = new Date();
    var curr_date = d.getUTCDate();
    var sup = "";
    if (curr_date == 1 || curr_date == 21 || curr_date == 31) {
        sup = "st";
    }
    else if (curr_date == 2 || curr_date == 22) {
        sup = "nd";
    }
    else if (curr_date == 3 || curr_date == 23) {
        sup = "rd";
    }
    else {
        sup = "th";
    }

    var curr_month = d.getUTCMonth();
    var curr_year = d.getUTCFullYear();

    //code for the time    
    var hours = d.getUTCHours()
    var minutes = d.getUTCMinutes()

    var suffix = "AM";
    if (hours >= 12) {
        suffix = "PM";
        hours = hours - 12;
    }
    if (hours == 0) {
        hours = 12;
    }

    if (minutes < 10)
        minutes = "0" + minutes;

    var datetimevalue = (m_names[curr_month] + " " + curr_date + ", " + curr_year + "  " + hours + ":" + minutes + " " + suffix);
    return datetimevalue;

}

1 comments:

Anonymous,  August 11, 2015 at 2:17 AM  

Thank You ,it helped me :-)