HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Day, month and year clone in to one with MomentJS

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
yearwithonemomentjsmonthanddayclone

Problem

There are two methods I am using here for merging day, month and year.

First one

$scope.firstOption = moment(new Date($scope.register.db.day + ' ' + $scope.register.db.month + ' ' + $scope.register.db.year));


Second One

$scope.secondOption = moment($scope.register.db.day + $scope.register.db.month + $scope.register.db.year).format('MMMM Do YYYY');


Unfortunately, there is a warning in the console which says:


Deprecation warning: moment construction falls back to js Date. This
is discouraged and will be removed in upcoming major release. Please
refer to https://github.com/moment/moment/issues/1407 for more info.
Arguments: [object Object]

Is there any best practice to clone those three fields?

Demo



angular.module('myApp', ['angularMoment']).controller('registerCtrl', function($scope, moment) {
console.log(moment('12-12-2020', 'DD-MM-YYYY').isValid());
$scope.registerMe = function(argument) {
$scope.firstOption = moment(new Date($scope.register.db.day + ' ' + $scope.register.db.month + ' ' + $scope.register.db.year));
console.log($scope.kooy);
$scope.secondOption = moment($scope.register.db.day + $scope.register.db.month + $scope.register.db.year).format('MMMM Do YYYY');
console.log($scope.keey);

};
});

`



Register your appointment




Name





Date of birth




Day
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22

Solution

All that fuss only meant: Moment will soon only parse ISO date strings. To parse arbitrary date strings reliably, you will need to describe the format via the second argument of the moment function. That's it.

$scope.date = moment($scope.register.db.day + $scope.register.db.month + $scope.register.db.year, 'DD MMMM YYYY');


Also, consider breaking out that string into variables and consider using template strings to assemble the date string:

let day = $scope.register.db.day;
let month = $scope.register.db.month;
let year = $scope.register.db.year;

$scope.date = moment(`${day} ${month} ${year}`, 'DD MM YYYY');


Aside from that, consider creating the dates, months and years selection in JS and just loop through it in the template.

Code Snippets

$scope.date = moment($scope.register.db.day + $scope.register.db.month + $scope.register.db.year, 'DD MMMM YYYY');
let day = $scope.register.db.day;
let month = $scope.register.db.month;
let year = $scope.register.db.year;

$scope.date = moment(`${day} ${month} ${year}`, 'DD MM YYYY');

Context

StackExchange Code Review Q#120377, answer score: 2

Revisions (0)

No revisions yet.