2

I have a HTML 5 input type="date".

<input type="date" required ng-model="nm.pick" id="dpicker ">

Then in my angular controller, I am assigning value

nm.pick = $filter("date")(Date.now(), 'dd/MM/yyyy');

Now this will give HTML5 default date format of yyyy-MM-dd.

But I want date format - dd/MM/yyyy

  1. I cannot changed <input type="date"> to <input type="text" in my HTML. If I change, dateformat will work fine
  2. Then I change input date to input text in controller

    $("#dpicker").attr("type", "text");
    nm.pick = $filter("date")(Date.now(), 'dd/MM/yyyy');
    

    which is not working.

Basically I want to change the dateformat to dd/MM/yyyy in controller without altering HTML.

What are all the possible way to achieve this?

2
  • Would you like to use moment? Commented May 25, 2017 at 12:01
  • yes definitely.. Commented May 25, 2017 at 12:02

2 Answers 2

5

The best way that i know is to use momentjs. I have used it with angular 1.x.x with no problems. It's pretty easy to use, check this out. You can add the following row:

nm.pick = moment(nm.pick).format('DD-MM-YYYY');

This should solve your problem,

Sign up to request clarification or add additional context in comments.

3 Comments

yeah..any brief way to use moment js for my problem?
Error: [ngModel:datefmt] Expected "2017-04-23T00:00:00.000Z"` to be a date` this error i'm getting... do i have to put new Date(date)?
@Arun, look through this post: stackoverflow.com/questions/30537886/… It looks like this problem has an answer already
3

For type="date" binding

var app = angular.module("MyApp", []).controller("MyCtrl", function($scope, $filter) {
  $scope.nm = {};
  $scope.nm.pick = new Date($filter('date')(new Date(), "yyyy-MM-dd"));
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>


<body ng-app="MyApp" ng-controller="MyCtrl">
    <input type="date" required ng-model="nm.pick" id="dpicker ">
</body>

Reading other answers, I'd advice the same to go with moment.js as it is an expert library when playing around with date/time and different timezone.

3 Comments

$filter doesnt work in my case, as i have mentioned above. failed to change format through momentjs also
Which version of angular are you using.. this should work fine on above 1.3
i am using 1.3.8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.