/**
* js/utils.js
* Utility functions for the rental car system.
*/
/**
* Formats a date string into a more readable format (e.g., "DD/MM/YYYY").
* @param {string} dateString - The date string (e.g., "YYYY-MM-DD").
* @returns {string} Formatted date string.
*/
export function formatDate(dateString) {
if (!dateString) return '';
try {
const date = new Date(dateString);
const day = String(date.getDate()).padStart(2, '0');
const month = String(date.getMonth() + 1).padStart(2, '0'); // Month is 0-indexed
const year = date.getFullYear();
return `${day}/${month}/${year}`;
} catch (e) {
console.error("Error formatting date:", e);
return dateString; // Return original if invalid
}
}
/**
* Calculates the total rental price based on car price per day and rental duration.
* @param {number} pricePerDay - The daily rental price of the car.
* @param {string} startDateString - The start date (YYYY-MM-DD).
* @param {string} endDateString - The end date (YYYY-MM-DD).
* @returns {number | null} Total price or null if dates are invalid.
*/
export function calculateRentalPrice(pricePerDay, startDateString, endDateString) {
if (!pricePerDay || !startDateString || !endDateString) {
return null;
}
try {
const startDate = new Date(startDateString);
const endDate = new Date(endDateString);
if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
console.error("Invalid start or end date for price calculation.");
return null;
}
// Calculate difference in days
const diffTime = Math.abs(endDate - startDate);
// Add 1 to include the last day. If pickup and return on same day, it's 1 day.
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
if (diffDays <= 0) {
return pricePerDay; // At least one day rental
}
return pricePerDay * diffDays;
} catch (e) {
console.error("Error calculating rental price:", e);
return null;
}
}