# Custom moment formats based on string length

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 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; } console.log(getDateFormat(dateString));  • 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.

http://jsfiddle.net/zb4sfno3/

• @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 – Johan Dec 11 '14 at 21:46