Angular 4输入类型日期格式

时间:2018-04-04 07:21:01

标签: angular angular4-forms

在项目编辑选项中,我有一个像这样的表格。如何将日期格式更改为dd / MM / yy。例如07/07/18,但它反映为全年。如何覆盖它?

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

2 个答案:

答案 0 :(得分:2)

将以下fiddler函数返回的值设置为模型并将其绑定到视图。 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));

答案 1 :(得分:1)

您应该使用<input type="text"和Regex将文本输入格式化为您想要的日期格式。有关正则表达式herehere

的更多信息