Vardaan Bhalla
Vardaan Bhalla

Reputation: 11

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

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.

Upvotes: 1

Views: 368

Answers (2)

M.Mutasim
M.Mutasim

Reputation: 51

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('-');
}

// 👇️ 2022-01-18 (yyyy-mm-dd)
console.log(formatDate(new Date()));

//  👇️️ 2025-05-09 (yyyy-mm-dd)
console.log(formatDate(new Date(2025, 4, 9)));

Upvotes: 0

Rav Singh Sandhu
Rav Singh Sandhu

Reputation: 62

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;

Upvotes: 0

Related Questions