0

I have a date in format dd/mm/yyyy and when I try to use getMonth() I get the dd field. For example if I have "01/12/2019" it will take 01 as month instead of 12. Is there a way to get the month from this format?

This is my code:

var beginDate = document.getElementById("beginDate").value;
var month = new Date(beginDate).getMonth();

inside beginDate there's "01/10/2019" (October 1st 2019)

Otori
  • 29
  • 1
  • 7

6 Answers6

2

It's better to use any external libraries like momentjs or datejs. Try this it may solve your problem now.

const date  = "01/12/2019";
const split = date.split('/');

console.log('day', split[0])
console.log('month', split[1])
console.log('year', split[2])

var date = moment('01/12/2019', 'DD/MM/YYYY');
console.log(date.month()+1);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
Yahiya
  • 761
  • 4
  • 15
1

You can use something like Moment.js

const beginDate = "22/05/2019"

const date = moment(beginDate, 'DD/MM/YYYY');

const month = date.format('M');

console.log(month)

//05
Lucas Meine
  • 1,524
  • 4
  • 23
  • 32
1

Make it easy. You don't need external libraries:

var beginDate = "01/10/2019";
var timeZone = 'your time zone'; //en-GB etc...
var month = new Date(beginDate).toLocaleString(timeZone , {month: "2-digit"}); //month = 10
Luca
  • 84
  • 1
  • 6
0

You can get months using getMonth() as shown below, But here 0=January, 1=February etc.

var date = "05/12/2019"
var d = new Date(date);
var n = d.getMonth();
console.log(n)
Saniya syed qureshi
  • 3,053
  • 3
  • 16
  • 22
0

I don't think that you need some external library to do this task. You should use javascript date object to get it done easily, getMonth() returns month indexed from 0 to 11. Prefer javascript always instead of unnecessarily importing external js files for libraries

var beginDate = document.getElementById("beginDate").value;

let reg = /(\d\d)\/(\d\d)\/(\d+)/gi;
const[date,mon,year] = reg.exec(beginDate).splice(1);       
month = new Date(year,mon-1,date).getMonth(); // months are indexed from 0 to 11 for jan to dec
console.log(month); // 0 for jan and 11 for dec
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29
0

Month in javascript is 0 indexed that mean 0 represent January, So you need to add 1 to get the month correctly

function getMonth(dt) {
  let splitDt = dt.split('/');
  return new Date(`${splitDt[2]}-${splitDt[1]}-${splitDt[0]}`).getMonth() + 1;
}

console.log(getMonth("01/10/2019"))
1st oct
brk
  • 48,835
  • 10
  • 56
  • 78