I have an asp.net web page that I need a javascript function to return the last day of a month based on a date passed from a TextBox. For example, if I pass 10/10/2014 I want it to return 10/31/2014. How can I do that in javascript? Thanks.
You could use a function like this :
function GetLastDayOfMonth(date){ // Attempt to parse the Date passed in var currentDate = new Date(date); // Get the last day of that month var targetDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0); return targetDate; }
You can see a working example here, which would return a Date object of "October 31st 2014" provided the input your example shows (10/10/2014). If you needed to actually output your Date in that format,
you would just need to adjust it slightly to handle the formatting :
function GetLastDayOfMonth(date){ // Attempt to parse the Date passed in var currentDate = new Date(date); // Get the last day of that month var targetDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0); // Outputs your date as a string in the format : "MM/dd/yyyy" return ('0' + (targetDate.getMonth()+1)).slice(-2) + '/' + ('0' + (targetDate.getDate())).slice(-2) + '/' + targetDate.getFullYear(); }
An example with formatting can be seen
here.
Perfect! Thanks.
One other question. When I use this js function on a TextBox with a CalendarExtender control and click on it after setting the value from the function, it does not show the new month but rather the old month before the change.