You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML表单如何按MM-DD-YYYY HH:MM AM/PM格式提交预约日期时间

Fixing Datetime Format for Form Submission

Hey there! I see the issue you're facing—let's get that datetime format sorted out for you. The datetime-local input type always submits values in ISO 8601 format (like 2018-03-06T12:59) by default, which is why your server is receiving that instead of the requested MM-DD-YYYY hh:mm AM/PM format. Here are two straightforward solutions to fix this:

Solution 1: Use a Hidden Input for the Formatted Date

This approach keeps the user-friendly datetime-local picker and converts the selected value to your desired format before submission, using a hidden input to send the correct string to the server.

Modified Code:

<!DOCTYPE html>
<html lang='en'>
<head>
<title>Form</title>
<script>
// Function to convert ISO date to the required format
function formatAppointmentDate() {
  const datePicker = document.getElementById("Appointment_Date");
  const hiddenInput = document.getElementById("Formatted_Appointment_Date");
  
  if (!datePicker.value) return; // Exit if no date is selected

  const selectedDate = new Date(datePicker.value);
  
  // Format month (01-12)
  const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
  // Format day (01-31)
  const day = String(selectedDate.getDate()).padStart(2, '0');
  const year = selectedDate.getFullYear();
  
  // Convert to 12-hour format with AM/PM
  let hours = selectedDate.getHours();
  const ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // Convert 0 (midnight) to 12
  
  // Format minutes (00-59)
  const minutes = String(selectedDate.getMinutes()).padStart(2, '0');
  
  // Build the final formatted string
  hiddenInput.value = `${month}-${day}-${year} ${hours}:${minutes} ${ampm}`;
}
</script>
</head>
<body>
<form action="/action_page.php" onsubmit="formatAppointmentDate()">
<div>
<label for="Appointment_Date"><font color="red">Appointment Date*:</font></label>
<!-- Keep the datetime-local picker for user input -->
<input type="datetime-local" id="Appointment_Date" name="Appointment_Date_Temp" required>
<!-- Hidden input to send the formatted date to the server -->
<input type="hidden" id="Formatted_Appointment_Date" name="Appointment_Date">
</div>
<div class="button">
<button type="submit">Submit</button>
</div>
</form>
</body>
</html>

How It Works:

  • The original datetime-local input is renamed to Appointment_Date_Temp so it doesn't get submitted to the server—its only job is letting users select a date/time.
  • When the form is submitted, formatAppointmentDate() runs, converts the selected date to your required format, and stores it in the hidden input.
  • The hidden input (named Appointment_Date) is what gets sent to your server with the correct format.

Solution 2: Intercept Form Submission and Modify the Data

If you prefer not to use a hidden input, you can intercept the form's submit event, reformat the date, and send the modified data directly.

Modified Code:

<!DOCTYPE html>
<html lang='en'>
<head>
<title>Form</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
  const form = document.querySelector('form');
  
  form.addEventListener('submit', function(e) {
    e.preventDefault(); // Stop the default form submission
    
    const datePicker = document.getElementById("Appointment_Date");
    if (!datePicker.value) {
      alert("Please select an appointment date!");
      return;
    }

    const selectedDate = new Date(datePicker.value);
    
    // Reuse the same formatting logic as Solution 1
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
    const day = String(selectedDate.getDate()).padStart(2, '0');
    const year = selectedDate.getFullYear();
    
    let hours = selectedDate.getHours();
    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12;
    
    const minutes = String(selectedDate.getMinutes()).padStart(2, '0');
    const formattedDate = `${month}-${day}-${year} ${hours}:${minutes} ${ampm}`;

    // Create FormData and replace the date value
    const formData = new FormData(form);
    formData.set('Appointment_Date', formattedDate);

    // Submit the modified form data using fetch
    fetch(form.action, {
      method: form.method,
      body: formData
    })
    .then(response => {
      // Handle post-submission actions (e.g., redirect or success message)
      window.location.href = "/action_page.php";
    })
    .catch(error => {
      console.error('Error submitting form:', error);
    });
  });
});
</script>
</head>
<body>
<form action="/action_page.php" method="POST">
<div>
<label for="Appointment_Date"><font color="red">Appointment Date*:</font></label>
<input type="datetime-local" id="Appointment_Date" name="Appointment_Date" required>
</div>
<div class="button">
<button type="submit">Submit</button>
</div>
</form>
</body>
</html>

Key Notes:

  • Time Zone: Both solutions use the user's local time. If you need UTC time instead, replace getMonth() with getUTCMonth(), getDate() with getUTCDate(), getHours() with getUTCHours(), etc.
  • Old Browser Compatibility: The padStart() method works in modern browsers. If you need to support older ones, replace it with a simple helper function:
    function padZero(number) {
      return number < 10 ? `0${number}` : number;
    }
    
    Then use padZero(selectedDate.getMonth() + 1) instead of String(...).padStart(2, '0').

内容的提问来源于stack exchange,提问作者Syed Shujah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:49:30