html 如何更改输入类型datetime-local的格式?

tv6aics1  于 2023-04-04  发布在  其他
关注(0)|答案(3)|浏览(122)

我给出了一个类型为datetime-local的输入字段,

<input type="datetime-local" class="form-control" name="booking_checkin">

在填完并看完之后,格式是这样的,
2017-08-06T02:32 .
看起来很尴尬,我需要改变这个模式
我希望有这样的格式,
2017-08-06, 02:32 .
我很抱歉没有张贴我所尝试的,因为我甚至没有一个启动的想法,以获得它后,搜索了很多在这里..请帮助我解决它..

qqrboqgw

qqrboqgw1#

在服务器端修改date

<?php 
$date = date('Y-m-d, h:i',strtotime($_POST['booking_checkin']));
?>
bvk5enib

bvk5enib2#

获取值时,它是有效的日期字符串,您可以将其传递给new Date,然后根据需要解析各个值

$('.form-control').on('change', function() {
	var parsed = new Date(this.value);
  var ten    = function(x) { return x < 10 ? '0'+x : x};
  var date   = parsed.getFullYear() + '-' + (parsed.getMonth() + 1) + '-' + parsed.getDate();
  var time   = ten( parsed.getHours() ) + ':' + ten( parsed.getMinutes() );
  
  console.log( date + ', ' + time)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="datetime-local" class="form-control" name="booking_checkin">

为了简单起见,使用jQuery与如何解析日期无关

g0czyy6m

g0czyy6m3#

要更改输入字段中显示的日期和时间的格式,可以使用JavaScript来操作输入字段的值。

<input type="datetime-local" class="form-control" name="booking_checkin" id="booking_checkin">

<script>
  // Get the input field element
  const input = document.getElementById('booking_checkin');

  // Add an event listener to the input field to detect when the value changes
  input.addEventListener('change', (event) => {
    // Get the value of the input field
    const value = event.target.value;

    // Convert the value to a Date object
    const date = new Date(value);

    // Format the date and time using the toLocaleString method
    const formattedDate = date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' });
    const formattedTime = date.toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit' });

    // Set the value of the input field to the formatted date and time
    event.target.value = `${formattedDate}, ${formattedTime}`;
  });
</script>

此代码侦听输入字段上的更改事件,然后使用Date对象的toLocaleString方法格式化值。然后将格式化的日期和时间设置为输入字段的值。
请注意,此代码假设用户的浏览器设置为en-US区域设置。如果应用程序支持多个区域设置,则可能需要相应地调整toLocaleDateString和toLocaleTimeString方法的参数。

相关问题