Just wanted to gage how solid this code is. With moment cracking down on lazy formatting I thought this was a good way to parse the string for what format to use.

var string = $this.attr("data-date");
var withoutTime = "YYMMDD";
var withTime = "YYMMDDHHmm";
var format = function(){
  if(string.length == withoutTime.length) return withoutTime;
  if(string.length == withTime.length) return withTime;
  return false;
var date = moment(string, format);

1 Answer 1


How about this (based on the assumption that $ refers to jQuery):

var dateString = $('div').data('date');

function getDateFormat(dateString){

    if(!dateString) return false;

    var dateTimeFormats = ['YYMMDD' ,'YYMMDDHHmm'];

    return dateTimeFormats.filter(function(format){
        return format.length === dateString.length;
    })[0] || false;

  • jQuery's data() method is preferred over attr() since it's intended to be used with either html5 data attributes (like in your case) or for caching data in the jQuery $.cache.

  • Try to use more descriptive names and don't use reserved keywords as variable names (or a close call like string vs String in your case).

  • Check if the date string is defined before making use of it

  • I suggest that you always do equality checks using the identity operator, ===. Otherwise you might get results like 1 == true since the type is not taken in to consideration

  • If you want to use Array.prototype.filter in IE < 9, you can add a shim.


  • \$\begingroup\$ @ThomasReggi My pleasure. As you can see, this code assumes that there is only one matching date pattern per length. If there are more, you'll get the first match in the array \$\endgroup\$
    – Johan
    Dec 11, 2014 at 21:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.