日期格式由JavaScript转换为dd/MM/YYYY



我想改变日期格式"dd/MM/YYYY"当我改变它给我另一个错误的日期。Adddate()函数设置默认到达日期和出发日期change - eddate()在更改到达日期时更改出发日期。

addDate();
function addDate() {
  date = new Date();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var year = date.getFullYear();
  if (document.getElementById('startDate').value == '') {
    document.getElementById('startDate').value = month + '/' + day + '/' + year;
  }
  if (document.getElementById('endDate').value == '') {
    document.getElementById('endDate').value = month + '/' + (day + 1) + '/' + year;
  }
}
function changedDate(){
  var arrivalDate = new Date(document.getElementById('startDate').value) ;
  var departureDate = new Date(document.getElementById('endDate').value) ;
  if(arrivalDate>=departureDate){
    var arrDate = new Date();
    arrDate.setDate(arrivalDate.getDate()+1);
    arrDate.setMonth(arrivalDate.getMonth()+1);
    arrDate.setFullYear(arrivalDate.getFullYear());
    document.getElementById('endDate').value = arrDate.getMonth() + '/' + arrDate.getDate() + '/' + arrDate.getFullYear();
  }
}
<input type="text" id="startDate" style="background-color:#5c677b;height:25px;" name="checkin" placeholder="checkin" onchange="changedDate()">
<input type="text" id="endDate" style="background-color:#5c677b;height:25px;" name="checkout" placeholder="checkout">

您已经分配了月+日+年。修改如下:

addDate();
function addDate() {
  date = new Date();
  var month = date.getMonth() + 1;
  if (month < 10)
    month = '0' + month;
  var day = date.getDate();
  if (day < 10)
    day = '0' + day;
  var year = date.getFullYear();
  if (document.getElementById('startDate').value == '') {
    document.getElementById('startDate').value = day + '/' + month + '/' + year;
  }
  if (document.getElementById('endDate').value == '') {
    document.getElementById('endDate').value = (day + 1) + '/' + month + '/' + year;
  }
}
function changedDate() {
  var startDate = document.getElementById('startDate').value.split("/");
  var endDate = document.getElementById('endDate').value.split("/");
  var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
  var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
  if (arrivalDate >= departureDate) {
    var arrDate = arrivalDate;
    arrDate.setDate(arrDate.getDate() + 1);
    var month = arrDate.getMonth() + 1;
    if (month < 10)
      month = '0' + month;
    var day = arrDate.getDate();
    if (day < 10)
      day = '0' + day;
    var year = arrDate.getFullYear();
    document.getElementById('endDate').value = day + '/' + month + '/' + year;
  }
}
<input type="text" id="startDate" style="background-color:#5c677b;height:25px;" name="checkin" placeholder="checkin" onchange="changedDate()">
<input type="text" id="endDate" style="background-color:#5c677b;height:25px;" name="checkout" placeholder="checkout">

有一个叫做moment.js的免费库,你可以很容易地使用日期格式。

moment().format('dd/MM/YYYY');

相关内容

  • 没有找到相关文章

最新更新