Search code examples
javascriptodatasapui5date-format

How to format a string like `2018911` into a Date?


From backend, the date format is like above, and I want to format the date using formatter into a real date. I got a datepicker in my detailpage and the datepicker wants a real date, to show it up.

So I tried a bit, but I can't get it to work. So maybe someone can help me or guide how to do it? I know I can format the date in the backend but I need it that way like above as a string.


Solution

  • Hi you can create a date from teh string you receiving by using below js code

     getDate:function(value){
    //value is your string from backend "20120515"
    if(value){
            var dateString  = value;
            var year        = dateString.substring(0,4);
            var month       = dateString.substring(4,6);
            var day         = dateString.substring(6,8);
    
            var date        = new Date(year, month-1, day);
    
        return date; // Keep in mind the date returned will only be correct if the string is passed in above format
        }
    }
    

    You can use the above function in formatter.js file and can use in datepicker as below

    <DatePicker value="{path:'modelDateProperty', formatter:'.formatter.getDate', }" />
    

    I hope this helps