Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate
" and the return value are strings.
For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API.
function formatDate(userDate)
{
userDate = new Date();
y = userDate.getFullYear();
m = userDate.getMonth();
d = userDate.getDate();
return y + m + d;
}
is there anything wrong with my code?
couldn't pass an online test.
Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate
" and the return value are strings.
For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API.
function formatDate(userDate)
{
userDate = new Date();
y = userDate.getFullYear();
m = userDate.getMonth();
d = userDate.getDate();
return y + m + d;
}
is there anything wrong with my code?
couldn't pass an online test.
Share Improve this question edited Feb 12, 2015 at 13:20 gvee 17.2k41 silver badges50 bronze badges asked Feb 12, 2015 at 12:18 MC JamesMC James 411 gold badge1 silver badge3 bronze badges 17 | Show 12 more comments12 Answers
Reset to default 12There are five problems with the code.
- It ignores the input parameter and uses the current time instead (
Date()
). - It assumes that the computer where it runs uses the m/d/y date format to parse the string (if it actually would have parsed the string).
- The
getMonth
method returns the month index, not the month number, so you have to add one to it. - It uses addition to put the values together instead of string concatenation.
- It doesn't format the month and date into two digits.
Ignoring the date format issue, the others can be fixed using:
function formatDate(userDate) {
userDate = new Date(userDate);
y = userDate.getFullYear().toString();
m = (userDate.getMonth() + 1).toString();
d = userDate.getDate().toString();
if (m.length == 1) m = '0' + m;
if (d.length == 1) d = '0' + d;
return y + m + d;
}
Instead of parsing the string to a date, and the format it to a string again, you can just rearrange the characters in the string. This circumvents the date format issue:
function formatDate(userDate) {
var parts = userDate.split('/');
if (parts[0].length == 1) parts[0] = '0' + parts[0];
if (parts[1].length == 1) parts[1] = '0' + parts[1];
return parts[2] + parts[0] + parts[1];
}
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
let array = userDate.split("/");
while(array[0].length < 2) {
array[0] = "0" + array[0];
}
while(array[1].length < 2) {
array[1] = "0" + array[1];
}
let arrayAnswer = array[2]+ array[0]+ array[1];
return arrayAnswer;
}
console.log(formatDate("1/3/2014"));
//output must equal 20140103
As a beginner, this was the simplest way I was able to do this one. It made more sense to me to split it up, add the 0's and then sort it into the correct places.
Follow through the comments in code - step by step showing one way of solving your problem.
// Function shell. Accepts a parameter userDate, returns a value
function formatDate(userDate) {
// Step 1: attempt to convert parameter to a date!
var returnDate = new Date(userDate);
// Step 2: now that this is a date, we can grab the day, month and year
// portions with ease!
var y = returnDate.getFullYear();
var m = returnDate.getMonth() + 1; // Step 6
var d = returnDate.getDate();
// Step 3: The bit we did above returned integer values. Because we are
// *formatting*, we should really use strings
y = y.toString();
m = m.toString();
d = d.toString();
// Step 4: The value of our month and day variables can be either 1 or 2
// digits long. We need to force them to always be 2 digits.
// There are lots of ways to achieve this. Here's just one option:
if (m.length == 1) {
m = '0' + m;
}
if (d.length == 1) {
d = '0' + d;
}
// Step 5: combine our new string values back together!
returnDate = y + m + d;
// Step 6: did you notice a problem with the output value?
// The month is wrong! This is because getMonth() returns a value
// between 0 and 11 i.e. it is offset by 1 each time!
// Look back up at Step 2 and see the extra piece of code
// Step 7: Looks pretty good, huh? Well, it might pass you your quiz
// question, but it's still not perfect.
// Do you know why?
// Well, it assumes that the parameter value is
// a) always an actual date (e.g. not "dave")
// b) our Step1 correctly converts the value (e.g. the client, where
// the JS is run, uses the date format m/d/y).
// I am in the UK, which doesn't like m/d/y, so my results will
// be different to yours!
// I'm not going to solve this here, but is more food for thought for you.
// Consider it extra credit!
return returnDate;
}
// Display result on page -->
document.getElementById("result").innerText += formatDate("1/1/2015");
<div id="result">Result: </div>
// format from M/D/YYYY to YYYYMMDD
function formatDate(userDate) {
var dateObj = new Date(userDate);
let year = dateObj.getFullYear();
let date = ('0' + (dateObj.getDate())).slice(-2);
let month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
return '' + year + month + date;
}
console.log("The converted date is : " , formatDate("12/31/2014"));
You are using +
with integers, you have to cast them as string.
function formatDate(userDate) {
userDate = new Date(userDate);
y = userDate.getFullYear();
m = userDate.getMonth() + 1;
d = userDate.getDate();
return y.toString() +
('0' + m.toString()).slice(-2) +
('0' + d.toString()).slice(-2);
}
And also you need to add leading zero to month and day.
Example:
console.log(formatDate('2/12/2015'));
will write to log 20150212
console.log(formatDate('1/1/2015'));
will write to log 20150101
function formatDate(userDate) {
var first = userDate.indexOf("/");
var last = userDate.lastIndexOf("/");
var months = userDate.substring(0, first);
var years = userDate.substring(last + 1);
var days = userDate.substring(last, 3);
return (years + months + days);
}
console.log(formatDate("12/31/2014"));
function formatDate(userDate) {
let userdate = userDate.split('/');
let [month, day, year] = userdate;
if (day.length === 1) {
day = `0${day}`;
}
if (month.length === 1) {
month = `0${month}`;
}
return `${year}${month}${day}`;
}
console.log(formatDate("12/1/2014"));
function formatDate(userDate) {
const month = userDate.substr(0, 2)
const day = userDate.substr(3, 2)
const year = userDate.substr(6)
return year + month + day
}
console.log(formatDate("12/31/2014"));
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
let [month,date,year] = userDate.split("/");
month = (month.length === 1) ? "0"+month : month;
date = (date.length === 1) ? "0"+date : date;
return year+month+date
}
console.log(formatDate("1/31/2014"));
function formatDate(userDate) {
// receiving m/d/yyyy
let userdate = userDate.split("/");
if(userdate[0].length == 1){userdate[0]='0'+userdate[0];}
if(userdate[1].length == 1){userdate[1]='0'+userdate[1];}
let temp = userdate[0];
userdate[0]=userdate[2];
userdate[2]=userdate[1];
userdate[1]=temp;
temp = userdate.join("");
return temp;
}
document.write("Our format = 12/31/2018");
document.write("<br />");
document.write("received format ="+formatDate("12/31/2018"));
document.write("<hr />");
document.write("Our format = 2/1/2018");
document.write("<br />");
document.write("received format ="+formatDate("2/1/2018"));
function formatDate(userDate) {
// format from M/D/YYYY to YYYYMMDD
var oldDate = String(userDate).split('/');
if (oldDate[0].length==1)oldDate[0]='0'+oldDate[0];
if (oldDate[1].length==1)oldDate[1]='0'+oldDate[1];
var newDate = [oldDate[2], oldDate[0], oldDate[1]];
return newDate.join('');
}
console.log(formatDate("12/31/2014"));
function formatDate(userDate) {
userDate = new Date(userDate);
year= userDate.getFullYear().toString();
month = (userDate.getMonth() + 1).toString();
date = userDate.getDate().toString();
return year + (month=(month.length==1)?'0'+month:month) + (date=(date.length==1)?'0'+date:date);
}
console.log(formatDate("12/10/2017"));
Some more details:
(1)userDate = new Date(userDate) => create an instance of Date object.
(2)userDate.getFullYear() is get year from userDate. Similarly user.getMonth() for month and userDate.getDate() for date...I've added +1 to month because month return is starts 0, i.e for month 6 it return 5 so 1 is added.
(3) in return statement year+month+date is done where there is tenary condition to check if month or date is single digit like 1 or 3 then 0 is added before it to make it 01 or 03.
1/1/2015
. This Your function converts this to201511
(if string concatenation) or2017
(if using arithmetic), which doesn't match on theMMDD
part (missing the leading zeroes)! – gvee Commented Feb 12, 2015 at 12:20;-)
. Have another attempt and see what you get up to – gvee Commented Feb 12, 2015 at 12:23;-)
– gvee Commented Feb 12, 2015 at 12:28