0

What is wrong with my code?

var myDate = new Date();
var myString = "" +
               ( (typeof myDate !== "undefined") && ((myDate.getUTCMonth() + 1) < 10) ? "0" : "" ) +
               ( typeof myDate !== "undefined" ? (myDate.getUTCMonth() + 1) + myDate.getUTCDate() + myDate.getUTCFullYear().toString().substr(2,2): "" );
return myString;

Why is my code returning 5 digits string such as "03116"? Is it because dates are assigned by reference?

EDIT: Thanks for the link. But it would really be helpful if someone had a clue about why am I getting a 5 digits string instead of MMDDYY. A have a lot lines based on this code and it would be painful to rewrite it without the concatenation.

EDIT2: Still would like to know what's wrong in the code? Is it because of assignation by reference?

Emilio
  • 1,314
  • 2
  • 15
  • 39
  • ok thanks, I'll try this one. – Emilio Sep 23 '16 at 03:19
  • @CORY Thanks for this answer ("0" + (date.getMonth() + 1).toString()).substr(-2) + ("0" + date.getDate().toString()).substr(-2) + (date.getFullYear().toString()).substr(2) – Emilio Sep 23 '16 at 03:27
  • 1
    It's not because of the Date, it's because the logic of the assignment to *myString* is not what you expect. The first part returns the string "0". The second part returns the current month 8 for September, adds 1 to get 9, then adds the date which (for me) is 23 so I get 32. The last part adds a 2 digit year as a string to make "3216" then the "0" is added to the front and the result is "03216". For you the date is 22 so you get "03116". – RobG Sep 23 '16 at 04:46
  • @RobG Thanks a lot for your answer. – Emilio Sep 23 '16 at 20:00

1 Answers1

-1

Use NSDateFormatter to convert the Date to String. For example

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM dd yy"
    return dateFormatter
    let myDate = Date();
    let str = dateFormatter.string(from: myDate)

If you merge the MMddyy it becomes unreadable, provide a space.

Sachin Vas
  • 1,757
  • 12
  • 16
  • A good answer should explain the OP's issue and how your code fixes that. Nor should it depend (or even use) on a library that isn't tagged or noted in the OP. – RobG Sep 23 '16 at 04:49
  • What does this have to do with JavaScript? – Pang Sep 23 '16 at 05:15