# Date composition from day, month and year input

I need to concatenate 3 input fields into a string which is formatted as a date dd-mm-yyyy, using type="date" or new Date() will not work in my scenario because Firebase doesn't allow it for some reason. I came up with a rather ugly solution, but I'm not quite sure how to improve it. delete is bad for performance, but I think that it is needed because I need to completely remove the properties from the object once they've been used.

$scope.addWeek = function(week) { var startDate = '' + week.startDate.day + '-' + week.startDate.month + '-' + week.startDate.year, endDate = '' + week.endDate.day + '-' + week.endDate.month + '-' + week.endDate.year; week.startDate = startDate; week.endDate = endDate; delete week.startDate.day; delete week.startDate.month; delete week.startDate.year; delete week.endDate.day; delete week.endDate.month; delete week.endDate.year; }  The week object looks like this: week = { number: 32, startDate: { day: 01, month: 07, year: 2015 }, endDate: { day: 08, month: 09, year: 2016 } }  After we're done it needs to look like this: week = { number: 32, startDate: 01-07-2015, endDate: 08-09-2016 }  Any suggestions on how to improve it? ## 3 Answers As Ekkhard.Homer said, none of you delete lines do anything, because startDate and endDate are strings at that point: They don't have any day, month or year properties. Anyway, since you need to do the same thing twice, I'd suggest you make a function for it. I've spruced this one up a bit by mapping properties, but that's not really necessary. $scope.addWeek = function(week) {

function formatDate(obj) {
return ['day', 'month', 'year'].map(function (prop) {
return String(obj[prop]);
}).join('-');
}

week.startDate = formatDate(week.startDate);
week.endDate = formatDate(week.endDate);
}

• Haha man I didn't even realise that I was overriding them. This is a good solution :) Jul 5, 2015 at 6:39

You may try something like this:

function parseDate(input) {
var str= input.split('/');
return new Date(str[0], str[1]-1, str[2]);
}


str[1]-1 as months starts from 0.

You may also check Date.parse(string) but this is implementation dependent.

• I think you got it backward. The code is not about parsing a string; it's about formatting a string. The output should be dd-mm-yyyy, not the input. Jul 4, 2015 at 16:58

It makes no sense at all to do something with 'week.startDate.day' (etc) after you assigned a string to week.startDate.