以YYYYMM日期格式设置月份的最后一天 - Javascript

时间:2017-05-02 18:25:55

标签: javascript

我的变量的日期值为YYYYMM格式。例如:

     var givenDate = "201704"

如何查找给定月份的最后一天并附加到该月份。例如,

     //last day of 2017 04 (April) is 30th so append value to givenDate + lastDate; 
     //that will be 20170430
      var newFullGivenDate = "20170430";

5 个答案:

答案 0 :(得分:4)



const date = "201704";
const year = parseInt(date.substring(0, 4));
const month= parseInt(date.substring(4, 6));
const lastDay = (new Date(year, month, 0)).getUTCDate();
const newFullGivenDate = date + lastDay;
console.log(newFullGivenDate);




答案 1 :(得分:1)



var givenDate = "201704";
var month = givenDate.substring(4, givenDate.length); // retrieves 04
var year = givenDate.substring(0, 4);                 // retrieves 2017

var d = new Date(year, month, 0);
alert(d.getDate());




参考:MDN

答案 2 :(得分:1)

要达到预期效果,请使用以下选项

每个月的最后一天 - 新日期(年,月,0)

var givenDate = "201704";
var currDate = new Date(givenDate.substr(0,3),givenDate.substr(4) ,0)
var newFullGivenDate = givenDate + currDate.getDate();
console.log(newFullGivenDate)

Codepen网址供参考 - https://codepen.io/nagasai/pen/OmgZMW

答案 3 :(得分:1)

我会把它分解成两个函数:

// Get last day from year and month
let lastDayOf = (year, month) => (new Date(year, month, 0)).getDate();

// Add last day to string only if input is correct
let addLastDay = (input) => {
  // In case you pass number (201705) instead of string ("201705")
  if (Number.isInteger(input)) input = input.toString();
  
  // Check if input is in correct format - 6 digit string
  if (typeof input !== "string" || !input.match(/^\d{6}$/)) {
    return input; // You can implement desired behavour here. I just return what came
  }
  
  const year = input.substr(0, 4);
  const month = input.substr(4, 2);
  
  return input + lastDayOf(year, month);
}

// Tests
console.assert(addLastDay("201704"), "20170430");
console.assert(addLastDay("201702"), "20170228");
console.assert(addLastDay("201202"), "20120229");
console.assert(addLastDay(201705), "20170531");
console.assert(addLastDay(20170), 20170); // Wrong input

// Interactive example
document.getElementsByTagName('button')[0].addEventListener('click', () => {
  let input = document.getElementsByTagName('input')[0];
  input.value = addLastDay(input.value);
});
<input type="text" value="201704"><button>Calculate</button>

答案 4 :(得分:0)

如果你正在使用时刻js,你可以这样说:

var date = moment(newFullGivenDate ).format('YYYYMMDD');

date = date.add(-1 * parseInt(date.format('DD')), 'days').add(1, 'months');