locked
how can I convert a string date using javascript? RRS feed

  • Question

  • When I query a date field, I am getting this: Sun Jun 02 2013 00:00:00 GMT+0100 (BST)

    But I need to convert the date to this: 2013-06-02

    How can I achieve this?

    Tuesday, June 18, 2013 7:10 PM

Answers

  • If you are reading the date from a date field, like for example:

    var createdon = Xrm.Page.getAttribute("createdon").getValue();

    you can convert the date object in this way:

    function ConvertDate(date) {
        var year = date.getFullYear()+'';
        var month = (date.getMonth() + 1)+'';
        if (month.length == 1)  month = "0" + month;
        var day = date.getDate()+'';
        if (day.length == 1)  day = "0" + day;
        return year + "-" + month + "-" + day;
    }
    
    var createdon = Xrm.Page.getAttribute("createdon").getValue();
    createdon = ConvertDate(createdon);


    My blog: www.crmanswers.net



    Tuesday, June 18, 2013 7:34 PM

All replies

  • If you are reading the date from a date field, like for example:

    var createdon = Xrm.Page.getAttribute("createdon").getValue();

    you can convert the date object in this way:

    function ConvertDate(date) {
        var year = date.getFullYear()+'';
        var month = (date.getMonth() + 1)+'';
        if (month.length == 1)  month = "0" + month;
        var day = date.getDate()+'';
        if (day.length == 1)  day = "0" + day;
        return year + "-" + month + "-" + day;
    }
    
    var createdon = Xrm.Page.getAttribute("createdon").getValue();
    createdon = ConvertDate(createdon);


    My blog: www.crmanswers.net



    Tuesday, June 18, 2013 7:34 PM
  • function FormatDate(fieldname) {
        var d = Xrm.Page.data.entity.attributes.get(fieldname).getValue();
        if (d != null) {
            var curr_date = d.getDate();
            var curr_month = d.getMonth();
            curr_month++;  // getMonth() considers Jan month 0, need to add 1
            var curr_year = d.getFullYear();
            return curr_date + "-" + curr_month + "-" + curr_year;
        }
        else return null

    If you find this helpful to you,please vote for my answer. thank you vasubabuk

    Wednesday, June 19, 2013 1:20 PM