0

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.

gvee
  • 16,732
  • 35
  • 50
MC James
  • 41
  • 1
  • 1
  • 3
  • 1
    Consider: `1/1/2015`. This Your function converts this to `201511` (if string concatenation) or `2017` (if using arithmetic), which doesn't match on the `MMDD` part (missing the leading zeroes)! – gvee Feb 12 '15 at 12:20
  • 2
    Actually your function doesn't format anything, it overrides the passed argument with a new Date and does some math with parts of that date. – Teemu Feb 12 '15 at 12:22
  • @gvee I see, so any solution on that? – MC James Feb 12 '15 at 12:22
  • @Teemu are you sure? – MC James Feb 12 '15 at 12:23
  • 1
    @MCJames you said that this is for an online test. I'm prodding you in the direction of the answer, not giving it to you `;-)`. Have another attempt and see what you get up to – gvee Feb 12 '15 at 12:23
  • @MCJames Yes, definitely. Just look at the code ... There's a ton of examples at SO about date formatting, you could try [one of them](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript). – Teemu Feb 12 '15 at 12:25
  • @MCJames okay, another prod in the right direction for *a* solution. You need to use strings. You need to force the MM and DD parts to always be 4 characters long (i.e. leading spaces). To do this you should add zeroes to the front of the string and then "chop" it to two characters from the right. – gvee Feb 12 '15 at 12:26
  • 1
    @gvee Yes, but before that OP has to parse the passed string, which is a big part of the whole idea of this homework. – Teemu Feb 12 '15 at 12:27
  • 1
    @Teemu I know, I didn't want to give the whole game away `;-)` – gvee Feb 12 '15 at 12:28
  • @Teemu are you a pro when you start to code? – MC James Feb 12 '15 at 12:38
  • 1
    @MCJames you are *learning* to code. Are you learning if the answers are just spoon fed to you? **You can** solve this problem `:-)` – gvee Feb 12 '15 at 12:45
  • 1
    @MCJames You've misunderstood my comment. The idea of the homeworks is, that you do them yourself, do some research, study things etc., not just copy-paste some code. – Teemu Feb 12 '15 at 12:46
  • @Teemu I tried and expect it work but it don't, that's why I come here.. I didn't copy paste anything! – MC James Feb 12 '15 at 12:58
  • @MCJames But you will ; ). – Teemu Feb 12 '15 at 13:04
  • @MCJames I've put together something for you here that should help. Please work through and ask any questions you might have. http://jsfiddle.net/errL8w1L/1/ (the next step is on http://jsfiddle.net/errL8w1L/2/ and so on) *EDIT: apologies for the inception style "Next step" links... I didn't think about how it was going to display properly! Your best bet is to overtype the URL in the browser bar* Final page here: http://jsfiddle.net/errL8w1L/9/ – gvee Feb 12 '15 at 13:05
  • @gvee thanks so much for your input! actually I just missed one thing, which is the character part.. anyway big thanks to you Gvee! – MC James Feb 12 '15 at 13:12
  • Which online test? – vol7ron Dec 08 '19 at 22:09

12 Answers12

12

There 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];
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • This assumes that `userDate` is always in the correct format `;-)` – gvee Feb 12 '15 at 12:30
  • if the date is 20, then + '0', won't it be 200? – MC James Feb 12 '15 at 12:32
  • 1
    for date 1/1/2015 `m = userDate.getMonth().toString();` will return `0`, because `getMonth()` is returning 0 - 11 – Legionar Feb 12 '15 at 12:47
  • @Legionar: Yes, that's right, I missed that. Thanks for spotting it. – Guffa Feb 12 '15 at 12:55
  • @MCJames: If the date is `20`, then it will be `"20"` as a string. As the length is not `1` there will not be a zero added. If the date is for example `5`, then the zero will be added before it: `"0" + "5"` gives `"05"`. – Guffa Feb 12 '15 at 12:57
  • @Guffa ah i see, I misunderstood it. I thought .length is to check the existence of it, like in jquery cases lol.. – MC James Feb 12 '15 at 13:00
3

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>
gvee
  • 16,732
  • 35
  • 50
  • why innerText +=, instead of innerText = ? – MC James Feb 12 '15 at 13:13
  • @MCJames `=` sets the value. `+=` *adds* to the existing value. If you look at the HTML, the word "Result" is *in* the `innerText` already. – gvee Feb 12 '15 at 13:17
  • ah I see.. instead of innerText, can I use text? – MC James Feb 12 '15 at 13:23
  • @MCJames Not in pure javascript, no. Next time you should try for yourself though! – gvee Feb 12 '15 at 13:26
  • I start with jquery, weak in pure js xD – MC James Feb 12 '15 at 13:37
  • @MCJames JQuery is nice, but for simple tasks it can be overkill. The function I have written doesn't use JQuery at all. – gvee Feb 12 '15 at 13:38
  • Hi. Can someone please tell me why am I getting the out as 20141203 when I enter formatDate("12/31/2014") – joekevinrayan96 Jan 28 '21 at 05:11
  • 1
    @JoeKevinRayan you found a bug in the code! I've updated the answer to correct this (it was calling `.getDay()` when it needed `.getDate()`!). Give it another whirl and let us know how you get on – gvee Jan 28 '21 at 10:32
3
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.

2

 // 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"));
Shikha Dev
  • 117
  • 1
  • 1
  • 4
0

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

Legionar
  • 7,472
  • 2
  • 41
  • 70
0
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"));
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68
fahreyad
  • 11
  • 1
0
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"));
SHR
  • 7,940
  • 9
  • 38
  • 57
0
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"));
derloopkat
  • 6,232
  • 16
  • 38
  • 45
0

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"));
Harish
  • 1
  • 1
0

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"));
Musaib Mushtaq
  • 407
  • 2
  • 8
  • 3
    When linking to your own site or content (or content that you are affiliated with), you [must disclose your affiliation _in the answer_](/help/promotion) in order for it not to be considered spam. Having the same text in your username as the URL or mentioning it in your profile is not considered sufficient disclosure under Stack Exchange policy. I'm not sure how the link is relevant to the answer. Please note that linking to your content *needlessly* is also considered spam. – cigien Jan 29 '22 at 15:51
-1
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"));
leap
  • 1
-1
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.

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
Farid Ansari
  • 813
  • 5
  • 7
  • @Pierre.Vriens (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. I hope this will make it clear. – Farid Ansari Dec 10 '17 at 23:38