Node.js
Date helpers
Add Date processing functions.
Date helpers
Now we add a date helper to the helpers object: formatDate. This method converts an ISO date string ("2024-03-15") into the "15.03.2024" format.
Example: helpers.formatDate = function(iso) { const [y, m, d] = iso.split("-"); return d + "." + m + "." + y; }. Here iso.split("-") splits the string at dashes and gives an array; [y, m, d] destructures it. The call helpers.formatDate("2024-03-15") returns 15.03.2024. This is a practical way to turn ISO dates into a displayable format. We take the previous lessons' solution and add this method.
Parsing with split
The split method splits a string at a given separator and gives an array. "2024-03-15".split("-") gives ["2024", "03", "15"]. With destructuring you assign each part to a separate variable.
Example: const [y, m, d] = iso.split("-");. Here y = "2024", m = "03", d = "15". Then you join the new order with d + "." + m + "." + y. Destructuring assigns the array's items to variables in order; the order matters. This technique is the basic way to pull data from structured strings like dates, times and CSV.
Exercise Add the formatDate method and call it
Take the previous lessons' solution. Add the helpers.formatDate method with body const [y, m, d] = iso.split("-"); return d + "." + m + "." + y;. Print the result with console.log(helpers.formatDate("2024-03-15")).
Show example solution
const helpers = {};
module.exports = helpers;
console.log("Ready");
helpers.capitalize = function(text) {
if (!text) return text;
return text[0].toUpperCase() + text.slice(1);
};
console.log(helpers.capitalize("hello"));
helpers.clamp = function(value, min, max) {
if (value < min) return min;
if (value > max) return max;
return value;
};
console.log(helpers.clamp(15, 0, 10));
helpers.formatDate = function(iso) {
const [y, m, d] = iso.split("-");
return d + "." + m + "." + y;
};
console.log(helpers.formatDate("2024-03-15"));
Test yourself
-
What does formatDate("2024-03-15") return?
helpers.formatDate("2024-03-15")
- "2024-03-15"
- "15.03.2024"
- "2024.03.15"
- "03.15.2024"
Show answer
"15.03.2024" — The format is day.month.year: 15.03.2024.
-
Match each piece to its role
- split("-")
- Splits the string at dashes
- [y, m, d]
- Takes parts with destructuring
- d + "." + m + "." + y
- Joins the new order
- iso
- Input date string
-
Complete the formatDate return
return ____ + "." + m + "." + y;
Show answer
return d + "." + m + "." + y;
Next lesson: Putting it together