Calendar Input Date Difference

User
$('#days_cnt').datepicker({
format: 'yyyy-mm-dd',
startDate: '-0d',
autoclose:true
});

// Event listener for date change
$('#days_cnt').on('change', function() {
var start_date_time_tt = $("#start_date_time").val();
console.log("Start Date Value:", start_date_time_tt);
const myArray = start_date_time_tt.split(" ");
var dateString = myArray[0];
var parts = dateString.split('-'); // Split the string by "-"
// Create a new date string in YYYY-MM-DD format
var formattedDateString = `${parts[2]}-${parts[1]}-${parts[0]}`;
console.log(myArray[0]);
if (start_date_time_tt) {
var startdate = new Date(formattedDateString);
var enddate = new Date($(this).val());
console.log("Start Date:", startdate);
console.log("End Date:", enddate);

// Calculate the difference in days
var day_diff = Math.ceil((enddate – startdate) / (1000 * 60 * 60 * 24)); // Convert milliseconds to days
console.log("Day Difference:", day_diff);

var report_days_val = $("#reminder_project_status").val();
var report_days_new;

if (report_days_val === '') {
report_days_new = day_diff;
} else {
report_days_new = report_days_val + ',' + day_diff;
}
$("#reminder_project_status").val(report_days_new);
} else {
alert("Please enter a valid start date.");
}
});
convert input box to calender then made below work

Assistant
To make your “ field a calendar and ensure the functionality of calculating the day difference works, follow these steps:

### Update HTML
Convert your input box into a calendar using the `datepicker` plugin and include a placeholder for your start date field:

<!-- Input field for selecting the end date -->
<input type="text" readonly id="days_cnt" placeholder="Calculate Days" />

<!-- Input field for selecting the start date -->
<input type="text" readonly id="start_date_time" placeholder="Start Date" />

<!-- Hidden input to store the result -->
<input type="hidden" id="reminder_project_status" />

### Update JavaScript
Here's the complete JavaScript code to make the calendar and functionality work properly:

// Initialize datepickers
$('#start_date_time, #days_cnt').datepicker({
    format: 'yyyy-mm-dd',
    startDate: '-0d',
    autoclose: true
});

// Event listener for date change
$('#days_cnt').on('change', function () {
    var start_date_time_tt = $("#start_date_time").val(); // Get the start date value
    console.log("Start Date Value:", start_date_time_tt);

    if (start_date_time_tt) {
        // Parse the start date into a proper format (YYYY-MM-DD)
        const startDateParts = start_date_time_tt.split('-');
        var formattedStartDate = `${startDateParts[0]}-${startDateParts[1]}-${startDateParts[2]}`;
        var startdate = new Date(formattedStartDate);

        // Get the selected end date
        var endDate = new Date($(this).val());
        console.log("Start Date:", startdate);
        console.log("End Date:", endDate);

        // Calculate the difference in days
        var day_diff = Math.ceil((endDate - startdate) / (1000 * 60 * 60 * 24)); // Convert milliseconds to days
        console.log("Day Difference:", day_diff);

        // Update the hidden input with the day difference
        var report_days_val = $("#reminder_project_status").val();
        var report_days_new;

        if (report_days_val === '') {
            report_days_new = day_diff;
        } else {
            report_days_new = report_days_val + ',' + day_diff;
        }

        $("#reminder_project_status").val(report_days_new); // Update the hidden input
    } else {
        alert("Please select a valid start date.");
    }
});

### Explanation
1. **Datepicker Initialization**: Both `#start_date_time` and `#days_cnt` are initialized as datepickers with the format `yyyy-mm-dd`.
2. **Start Date Validation**: Ensure the start date (`#start_date_time`) is selected before calculating the day difference.
3. **Date Difference Calculation**: The code calculates the difference in days between the selected start date and the `#days_cnt` date.
4. **Update Hidden Input**: The difference is stored in `#reminder_project_status`.

### Prerequisites
Make sure you include the necessary libraries for the `datepicker` to function:

<!-- Bootstrap CSS (for styling the datepicker) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- Datepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" />

This setup will make the inputs functional calendars and allow you to calculate the difference in days correctly.

User
No make calender button
Assistant
To create a calendar button that triggers the date picker when clicked, you can add a button next to the input field. Here's how you can implement it:

### Updated HTML

<!-- Input field for the start date -->
<div>
    <input type="text" readonly id="start_date_time" placeholder="Start Date" />
    <button type="button" id="start_date_btn">๐Ÿ“…</button>
</div>

<!-- Input field for the end date -->
<div>
    <input type="text" readonly id="days_cnt" placeholder="Calculate Days" />
    <button type="button" id="end_date_btn">๐Ÿ“…</button>
</div>

<!-- Hidden input to store the result -->
<input type="hidden" id="reminder_project_status" />

### Updated JavaScript

// Initialize datepickers for inputs
$('#start_date_time, #days_cnt').datepicker({
    format: 'yyyy-mm-dd',
    startDate: '-0d',
    autoclose: true
});

// Trigger the datepicker for the start date when the button is clicked
$('#start_date_btn').on('click', function () {
    $('#start_date_time').datepicker('show');
});

// Trigger the datepicker for the end date when the button is clicked
$('#end_date_btn').on('click', function () {
    $('#days_cnt').datepicker('show');
});

// Event listener for the end date change
$('#days_cnt').on('change', function () {
    var start_date_time_tt = $("#start_date_time").val(); // Get the start date value
    console.log("Start Date Value:", start_date_time_tt);

    if (start_date_time_tt) {
        // Parse the start date into a proper format (YYYY-MM-DD)
        const startDateParts = start_date_time_tt.split('-');
        var formattedStartDate = `${startDateParts[0]}-${startDateParts[1]}-${startDateParts[2]}`;
        var startdate = new Date(formattedStartDate);

        // Get the selected end date
        var endDate = new Date($(this).val());
        console.log("Start Date:", startdate);
        console.log("End Date:", endDate);

        // Calculate the difference in days
        var day_diff = Math.ceil((endDate - startdate) / (1000 * 60 * 60 * 24)); // Convert milliseconds to days
        console.log("Day Difference:", day_diff);

        // Update the hidden input with the day difference
        var report_days_val = $("#reminder_project_status").val();
        var report_days_new;

        if (report_days_val === '') {
            report_days_new = day_diff;
        } else {
            report_days_new = report_days_val + ',' + day_diff;
        }

        $("#reminder_project_status").val(report_days_new); // Update the hidden input
    } else {
        alert("Please select a valid start date.");
    }
});

### Explanation
1. **Calendar Buttons**: Buttons (`#start_date_btn` and `#end_date_btn`) are placed next to the input fields. When clicked, they trigger the respective date pickers.
2. **Date Picker Trigger**: The `.datepicker('show')` method opens the date picker for the corresponding input field.
3. **Date Difference Calculation**: The logic for calculating the day difference remains the same.

### Example Styling (Optional)
To style the buttons, you can add simple CSS:

<style>
button {
    margin-left: 5px;
    cursor: pointer;
    border: 1px solid #ccc;
    background-color: #f8f9fa;
    padding: 5px;
    border-radius: 3px;
}
button:hover {
    background-color: #e2e6ea;
}
</style>

### Prerequisites
Include the same libraries mentioned in the previous message to use the date picker. This approach provides a user-friendly way to open the calendar using dedicated buttons.

Leave a Comment

Your email address will not be published. Required fields are marked *