0

How to get the start of the month in date format e.g. 01-05-2017?

I have already seen

Get first and last date of current month with javascript or jquery

marmeladze
  • 6,468
  • 3
  • 24
  • 45
Kirnc
  • 23
  • 8

3 Answers3

1

If I understand correctly toLocaleString() might do what you want. For example:

lastDay.toLocaleString('en-GB', {day: 'numeric', month: '2-digit', year: 'numeric'});

For more info (MDN)

Replace locale with any that suits your desired formatting.

e-shfiyut
  • 3,538
  • 2
  • 30
  • 31
Rainer
  • 29
  • 5
0

After getting the date we need to convert it to desired string format.

01 is the day and may be a constant since every beginning of the month starts from 1.

getMonth returns number of the month starting from 0 so we need a little function to format it.

var date = new Date();
var startDate = new Date(date.getFullYear(), date.getMonth(), 1);
var startDateString = '01-' + fotmatMonth(startDate.getMonth()) + '-' + startDate.getFullYear();
console.log(startDateString);

function fotmatMonth(month) {
  month++;
  return month < 10 ? '0' + month : month;
}
Jurij Jazdanov
  • 1,248
  • 8
  • 11
0
var date = new Date();
console.log(getStartOfMonthDateAsString(date));

function getStartOfMonthDateAsString() {        
  function zerosPad(number, numOfZeros) {
    var zero = numOfZeros - number.toString().length + 1;
    return Array(+(zero > 0 && zero)).join("0") + number;
  }

  var day = zerosPad(1, 2);
  var month = zerosPad((date.getMonth() + 1), 2);
  var year = date.getFullYear();

  return day + '-' + month + '-' + year;
}
e-shfiyut
  • 3,538
  • 2
  • 30
  • 31