...

View Full Version : snippet: convert months to numbers (when you fetch it from DB or something)



Peeyush
05-14-2012, 03:29 PM
function assignmonth()
{
g = (e==" January ")? 1 : (e==" February ")? 2 : (e==" March ")? 3 : (e==" April ")? 4 : (e== " May ")? 5 : (e== " June ")? 6 : (e==" July ")? 7: (e==" August ")? 8 : (e==" September ")? 9 : (e==" October ")? 10 : (e==" November ")? 11 : (e==" December ")? 12 : false ;
}

Note: Take care of the spaces for example, i have posted (e==" January ") not (e=="January"), and g will have value 'false' or 'NaN' when neither of the cases is true, which could mean there is some error

DJCMBear
05-14-2012, 03:45 PM
Why not something like this which returns false if nothing found so you are able to use it in an if statement and be able to check if a month was found.



(function ($) {
var Months = {"january": 1, "febuary": 2, "march": 3, "april": 4, "may": 5,
"june": 6, "july": 7, "august": 8, "september": 9,
"october": 10, "november": 11, "december": 12};
$.assignMonth = function (month) {
return ((month = Months[month.toLowerCase().replace(/\s/g, "")])) ? month : false;
};
}(window));

devnull69
05-14-2012, 04:00 PM
And it should definitely return 0 for January, 1 for February and so on because internally this is how Javascript date formats will represent the months anyway.

DJCMBear
05-14-2012, 04:05 PM
Who says that Javascript will be running the output through the date function?

All the OP was doing is outputting the numeric value for the corresponding month in humanly readable counts (e.g January = 1 not 0).

If however you want to get the Javascript internal value then this will do it.



(function ($) {
var Months = {"january": 1, "febuary": 2, "march": 3, "april": 4, "may": 5,
"june": 6, "july": 7, "august": 8, "september": 9,
"october": 10, "november": 11, "december": 12};
$.assignMonth = function (month, internal) {
return ((month = Months[month.toLowerCase().replace(/\s/g, "")])) ?
(internal && internal === true ? month - 1 : month) : false;
};
}(window));




// Standard
assignMonth(" January "); // 1

// Internal
assignMonth(" January ", true); // 0

Peeyush
05-14-2012, 04:36 PM
I was trying to assign numbers to months, first did it in if, else if format, then i remembered about this conditional operator so i posted it her thinking it might be useful to others, and i hope it is. am gonna post a few more soon

DJCMBear
05-14-2012, 04:44 PM
That is good however I still say instead of 13 it should be false, Meaning nothing found.

Peeyush
05-14-2012, 05:20 PM
thanks :) btw posted a new snippet here : http://www.codingforums.com/showthread.php?p=1228438#post1228438



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum