Pushparaj
Pushparaj

Reputation: 1080

Angular 4 input type date format

In item edit option i had a form like this.how to change date format as dd/MM/yy.for example 07/07/18 but its reflecting as full year.how to override this?

<input type="date"  class="form-control" name="published" #published [(ngModel)] = "books.published"  [ngModelOptions]="{ standalone: true }"/>

Upvotes: 1

Views: 3333

Answers (2)

vijesh
vijesh

Reputation: 1173

Set the value returned by the below fiddler function to your model and bind it to your view. jsfiddle

 //A function for formatting a date to MM/dd/yy
    function formatDate(d)
    {
        //get the month
        var month = d.getMonth();
        //get the day
        //convert day to string
        var day = d.getDate().toString();
        //get the year
        var year = d.getFullYear();

        //pull the last two digits of the year
        year = year.toString().substr(-2);

        //increment month by 1 since it is 0 indexed
        //converts month to a string
        month = (month + 1).toString();

        //if month is 1-9 pad right with a 0 for two digits
        if (month.length === 1)
        {
            month = "0" + month;
        }

        //if day is between 1-9 pad right with a 0 for two digits
        if (day.length === 1)
        {
            day = "0" + day;
        }

        //return the string "MMddyy"
        return month +'/'+ day +'/'+ year;
    }

    var d = new Date();
    alert(formatDate(d));

Upvotes: 2

Joe Belladonna
Joe Belladonna

Reputation: 1339

You should use <input type="text" and Regex to format your text input to a date format you want. More on regex here and here

Upvotes: 1

Related Questions