flatpker

by jimkennelly

HTML

<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
Usage
this is flat picker time date picker
<input type-"text" id="dtpicker">

CSS

.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}

JavaScript

// Assuming you have a flatpickr instance initialized like this:
const fp = flatpickr("#dtpicker", {
  enableTime: true,
  dateFormat: "Y-m-d H:i", // Adjust as needed
  defaultDate: new D
  // ... other options
});

function configureFlatpickrWithUTC() {
  // 1. Set default date in UTC, but display local time.
  const nowUtc = new Date(); // Get current UTC time.
  const nowLocal = new Date(nowUtc.getTime() - nowUtc.getTimezoneOffset() * 60000); // Convert UTC to local.
  alert(nowLocal)
  fp.setDate(nowLocal, false); // Set local date, but don't trigger onChange.

  // 2. Set max date in UTC, but display local time.
  const maxUtc = new Date(); // Example: Dec 31, 2024, 23:59:59 UTC
  const maxLocal = new Date(maxUtc.getTime() - maxUtc.getTimezoneOffset() * 60000); // Convert UTC to local.

  fp.set("maxDate", maxLocal);

  // 3. When getting the selected date, convert it back to UTC if needed.
  fp.config.onChange.push(function(selectedDates, dateStr, instance) {
    if (selectedDates.length > 0) {
      const selectedLocal = selectedDates[0];
      const selectedUtc = new Date(selectedLocal.getTime() + selectedLocal.getTimezoneOffset() * 60000);

      // Now you have the selected date in UTC.
      console.log("Selected UTC:", selectedUtc.toISOString());

      // You can also get it as a local string for display.
      console.log("Selected Local:", selectedLocal.toISOString());

      // Do something with the UTC date (e.g., send it to a server).
    }
  });
}

configureFlatpickrWithUTC();