patternjavascriptMinor
Custom moment formats based on string length
Viewed 0 times
lengthcustombasedformatsmomentstring
Problem
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);Solution
How about this (based on the assumption that
-
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
-
Try to use more descriptive names and don't use reserved keywords as variable names (or a close call like
-
Check if the date string is defined before making use of it
-
I suggest that you always do equality checks using the identity operator,
-
If you want to use Array.prototype.filter in IE
http://jsfiddle.net/zb4sfno3/
$ 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
http://jsfiddle.net/zb4sfno3/
Code Snippets
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));Context
StackExchange Code Review Q#73363, answer score: 3
Revisions (0)
No revisions yet.