Home > Software design >  How to remove time dependancy on Max and Min Dates in Date Picker in datetime mode?
How to remove time dependancy on Max and Min Dates in Date Picker in datetime mode?

Time:12-19

In my project, I have to set minimum and maximum dates in DateTimePicker. Although it has both date and time components, I just want to select min and max dates and not min and max time. So, for example, if minimumDate is 19 December 2022, the user can select any time from 00:00 to 23:59 of 19 December. How can I do this?

Please help wrt React Native and Javascript.

CodePudding user response:

import React from 'react';

function MyDateTimePicker() {
  return (
    <input
      type="datetime-local"
      min={new Date(2022, 11, 19, 0, 0, 0).toISOString().slice(0, -1)}
      max={new Date(2022, 11, 21, 23, 59, 59).toISOString().slice(0, -1)}
    />
  );
}

export default MyDateTimePicker;

CodePudding user response:

Use this function of getting exact Date formats and pass it to min max props or wherever you want

const date = new Date();

// ✅ Reset a Date's time to midnight
date.setHours(0, 0, 0, 0);

// ✅ Format a date to YYYY-MM-DD (or any other format)
function padTo2Digits(num) {
  return num.toString().padStart(2, '0');
}

function formatDate(date) {
  return [
    date.getFullYear(),
    padTo2Digits(date.getMonth()   1),
    padTo2Digits(date.getDate()),
  ].join('-');
}

//            
  • Related