3

I want to get date of birth of a user, with predefined min and max date which is working fine. And the date format i want is DD-MM-YYYY, for this i have defined following in config;

app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
      $mdDateLocaleProvider.formatDate = function(date) {
         return moment(date).format('DD-MM-YYYY');
      }}]);

and the controller has

    $scope.user = {};
    $scope.user.dob = new Date();
    $scope.maxDate = new Date(
       $scope.user.dob.getFullYear() - 10,
       $scope.user.dob.getMonth(),
       $scope.user.dob.getDate()
    );
    $scope.minDate = new Date(
       $scope.user.dob.getFullYear() - 120,
       $scope.user.dob.getMonth(),
       $scope.user.dob.getDate()
    );

and the HTML is;

<md-datepicker 
 ng-model="user.dob" 
 md-placeholder="Enter date of birth"
 md-min-date="minDate" 
 md-max-date="maxDate">
</md-datepicker>

with this code the field shows current date by default, which i don't want,

i want the date field to be empty by default.

Also i want to get values in both ways as follows 1) date-month-year And 2) date-month-year hour-minutes-seconds

When i tried to get the value it shows this "09-11-2016T18:30:00.000Z"

i want either "09-11-2016" or "09-11-2016 18:30:00"

1
  • If i remove code written in config block then the field value does not show any date, but this prevents me from setting a particular date format. Commented Nov 10, 2016 at 15:22

2 Answers 2

5

Your mdDateLocaleProvider doesnt check for null values.

Your Problem is:

app.config(['$mdDateLocaleProvider', function ($mdDateLocaleProvider) {
  $mdDateLocaleProvider.formatDate = function(date) {
     return moment(date).format('DD-MM-YYYY');
  }}]);

it needs to be something like:

$mdDateLocaleProvider.formatDate = function(date) {
   var m = moment(date);
   return m.isValid()? m.format('DD-MM-YYYY') : '';
};

Then you can set

$scope.user.dob=null;

And get an empty Datepicker.

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

Comments

0

The problem is your ng-model. You're initializing it with the current date:

$scope.user.dob = new Date();

Simply empty this variable and you'll be good ;)

1 Comment

i tried $scope.user.dob = ""; and $scope.user.dob = null; but both results in "Invalid date" and $scope.user.dob = undefined; shows current date

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.