jquery - Unable to roll over date to 2015 -
i have script gets me date of lastmonth
, current month
, next month
. see below
$(document).ready(function () { var d = new date(); var monthnames = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]; var pastmonth = monthnames[d.getmonth() - 1].tostring(); alert('past month: ' + pastmonth); var monthlymonth = monthnames[d.getmonth()].tostring(); alert('current month: ' + monthlymonth); var futuremonth = monthnames[d.getmonth() + 1].tostring(); alert('future month: ' + futuremonth); //error on here , not sure why });
i think problem adding month our current month , roll on new year 2015
, breaks.
i have been reading few threads , cannot find answer this. broke entered december
, has been working fine other 2014
months.
here fiddle of issue.
anybody experienced same problem , me out links threads may me?
edit: - need future month january
you have array of months , trying access var futuremonth = monthnames[d.getmonth() + 1].tostring();
. here d.getmonth() + 1
13 , month has 12 elements; hence giving array out of index exception.
you can overcome problem using %12
calculating monthnames array index.
try below code :
var pastmonth = monthnames[(d.getmonth() - 1)%12].tostring(); alert('past month: ' + pastmonth); var monthlymonth = monthnames[(d.getmonth())%12].tostring(); alert('current month: ' + monthlymonth); var futuremonth = monthnames[(d.getmonth() + 1)%12].tostring(); alert('future month: ' + futuremonth);
edit - above solution fail if current month january d.getmonth()=0
, overcome problem need update below code -
var pastmonth = monthnames[(d.getmonth() > 0)?((d.getmonth() - 1)%12):11].tostring();
Comments
Post a Comment