Solution for Rosetta Code: Date format

A small error in the problem statement has been reported here: "Rosetta Code: Date format" sample day is incorrect · Issue #39997 · freeCodeCamp/freeCodeCamp · GitHub

What is your hint or solution suggestion?
The full days and months of the year cannot be retrieved from the Date object, so separate arrays have to be created from them.

The first format is an ISO String format, which can be returned using .toISOString() and two separators. Other methods to return various components, for instance, are .getDate() and .getFullYear()

Solution 1
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

function getDateFormats() {
  var d = new Date;
  var str = d.toISOString().split('T')[0].split('-0').join('-');

  var day = days[d.getDay()];
  var month = months[d.getMonth()];

  var str1 = day + ", " + month + " " + d.getDate() + ", " + d.getFullYear() 
  console.log([str,str1])
  return [str,str1];
}

Challenge: Date format

Link to the challenge:

This solution actually won’t work right now because the test requires no trailing zeros for the first value.

1 Like

Thanks for pointing that out. This is easily fixable by adding .split('-0').join('-') to the str variable.

Right, there are solutions to it. There is also a discussion in another thread about changing the unit test to accept either format.

The full days and months of the year cannot be retrieved from the Date object, so separate arrays have to be created from them.

Well, they actually can:

const date = new Date();

console.log(date.toLocaleDateString('en-US', { weekday: 'long' }));
// Monday (or whatever)

console.log(date.toLocaleDateString('en-US', { month: 'long' }));
// March (or whatever)

Perhaps that could be an alternate solution.

1 Like