Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get month range by month name

I have a jQuery onclick function which basically receives a month name, and from that month name, I would like to get a month range. Like for instance I'm passing a month name "May" like this:

 $('#swiperNext').click(function(e)
   {
       var currentMonth = $('.swiper-slide-active h3').html();
       console.log(currentMonth);
   });

Now I'd like to pass the current month name to a JS function and get date range for that month.

So for example May would be => 01-05-2016 - 31-05-2016, so on and so on... Can someone help me out with this ?

like image 868
perkes456 Avatar asked Apr 22 '26 07:04

perkes456


2 Answers

You can do it without any third party library like this.

I presume you are calculation for current year

var date = new Date();
var y = date.getFullYear();
var month = $('.swiper-slide-active h3').text();
var m = new Date(Date.parse(month, 1, " + y)).getMonth();

var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT: I have changed the answer to use a month name as a string

like image 83
Ales Maticic Avatar answered Apr 23 '26 19:04

Ales Maticic


I would use Moment.js. It is perfect for manipulating dates and do all sorts of things.

In your specific case:

var startOfMonth = moment().month("June").startOf("month").toDate()
var endOfMonth   = moment().month("June").endOf("month").toDate()
like image 32
Oscar Eduardo Avatar answered Apr 23 '26 19:04

Oscar Eduardo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!