Skip to content

Instantly share code, notes, and snippets.

@dantswain
Last active August 29, 2015 14:17
Show Gist options
  • Save dantswain/c3709e249a174d42e59a to your computer and use it in GitHub Desktop.
Save dantswain/c3709e249a174d42e59a to your computer and use it in GitHub Desktop.
Javascript Shaming

To produce a string a la '2015-03-25' for the current date

In Ruby:

require 'date'
d = Date.today
puts d.to_s

In Javascript:

// have to roll our own number padder
// at least we can cheat because n should never be > 31
function pad2(n) {
  if(n < 10){
    return '0' + n;
  } else {
    return '' + n;
  }
}

function formatDate(date) {
  // what does date.getYear() return?  does it return 2015?
  // no?  maybe years since the standard unix epoch (1/1/1970)?
  // nope.  years since 1900.
  var year = 1900 + date.getYear();
  
  // what does date.getMonth() return?  the month number,
  // and of course January is the zeroth month.
  var month = 1 + date.getMonth();
  
  // date.getDay() should return the day of the month right?  
  // NO.  date.getDate() does... 
  var day = date.getDate();
  
  return year + '-' + pad2(month) + '-' + pad2(day);
}

var today = new Date();
console.log(formatDate(today));

Let it sink in that calling toDate on a Date object returns the day of month.

@jrgarcia
Copy link

var today = new Date();
console.log(today.toISOString().split('T')[0])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment