如何从输入获取格式日期?

时间:2019-06-03 13:20:31

标签: javascript jquery

我有日期字段的输入控件。我希望将日期设置为2/2/2019之类的格式。在下面的代码output中是:02/02/2019

示例代码:

var date = new Date($('#AppointmentDate').val());
var formatted = ('00' + date.getDate()).slice(-2) + '/' + ('00' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear();

console.log(formatted);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="02/02/19 12:00:00 AM">

3 个答案:

答案 0 :(得分:2)

如果日期小于10,您的代码会附加0。只需删除该代码即可:

var date = new Date($('#AppointmentDate').val());
var formatDate =getFormattedDate(date);
console.log(formatDate);

function getFormattedDate(date) {
  var year = date.getFullYear();

  var month = (1 + date.getMonth()).toString();

  var day = date.getDate().toString();
  
  return month + '/' + day + '/' + year;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="2/2/19 12:00:00 AM">

再次进行编辑,删除添加零的代码:

var date = new Date($('#AppointmentDate').val());
var formatted = ('' + date.getDate()).slice(-2) + '/' + ('' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear();

console.log(formatted);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="02/02/19 12:00:00 AM">

答案 1 :(得分:-1)

您可以使用parseInt删除前面的零

答案 2 :(得分:-1)

应用HTML:

<input type="text" data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="2/2/19 12:00:00 AM">

应用JavaScript:

function getFormattedDate(date) {
  var year = date.getFullYear();
  var month = (1 + date.getMonth()).toString();
  var day = date.getDate().toString();
  return month + '/' + day + '/' + year;
}