2
\$\begingroup\$

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?

\$\endgroup\$
2
\$\begingroup\$

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);
}
\$\endgroup\$
  • \$\begingroup\$ Haha man I didn't even realise that I was overriding them. This is a good solution :) \$\endgroup\$ – Chrillewoodz Jul 5 '15 at 6:39
1
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Flambino Jul 4 '15 at 16:58
0
\$\begingroup\$

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.