Problem 4: format a Date Object to use a given date string format. Building on your work
Question:
Problem 4: format a Date Object to use a given date string format.
Building on your work in Problem 3 above, we want to be able to take a Date
object, and format it into a string using one of the following 3 formats:
1. YYYY/MM/DD
2. DD/MM/YYYY
3. MM/DD/YYYY
Meaning, Year (4 digits), Month (2 digits), Day (2 digits).
Write a function, toDateString() that accepts a Date object and a date string
format (e.g., "YYYY/MM/DD", "DD/MM/YYYY", or "MM/DD/YYYY"), and returns a date
string formatted according to the supplied format. Make sure your day and month
values are padded with a leading '0' if necessary (e.g., 03 vs. 3).
If something other than a valid Date Object is passed as the first argument,
trying to call the Date methods will fail. You should use try/catch and
throw a new Error object with an appropriate error message if this happens.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
If the date string format is not one of the 3 listed above, throw a new Error
with an appropriate error message explaining the problem.
NOTE: it should be possible to use parseDateString() from the previous question
and toDateString() to reverse each other. For example:
toDateString(parseDateString('2021/01/29), "YYYY/MM/DD") should return '2021/01/29'
toDateString(parseDateString('2021/01/29), "DD/MM/YYYY") should return '29/01/2021'
toDateString(parseDateString('29/01/2021), "MM/DD/YYYY") should return '01/29/2021'
@param {Date} value - a Date Object to be formatted
@param {string} format - a format string, one of "YYYY/MM/DD", "DD/MM/YYYY", or "MM/DD/YYYY"
@returns {string} - the formatted date string
******************************************************************************/
function toDateString(value, format) {
// Replace this comment with your code...
}
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill