marco.pms.web/src/utils/dateUtils.jsx

108 lines
2.9 KiB
JavaScript

import moment from "moment";
import { ActiveTenant } from "./constants";
import {format} from 'date-fns'
export const getDateDifferenceInDays = (startDate, endDate) => {
if (!startDate || !endDate) {
return null;
}
const start = new Date(startDate);
const end = new Date(endDate);
if (isNaN(start) || isNaN(end)) {
return null;
}
const startAtMidnight = new Date(
start.getFullYear(),
start.getMonth(),
start.getDate()
);
const endAtMidnight = new Date(
end.getFullYear(),
end.getMonth(),
end.getDate()
);
return Math.floor((startAtMidnight - endAtMidnight) / (1000 * 60 * 60 * 24));
};
export const formatDate = (date) => {
if (!date) return ""; // Return an empty string if no date
const dateObj = new Date(date);
// return dateObj.toISOString().split("T")[0];
return dateObj.toLocaleDateString('en-CA'); // Get the date in YYYY-MM-DD format
};
export const convertShortTime = (dateString) => {
const date = new Date(dateString);
let hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, "0");
const ampm = hours >= 12 ? "PM" : "AM";
hours = hours % 12; // Convert to 12-hour format
hours = hours ? hours : 12; // If hours is 0, set it to 12
return `${String(hours).padStart(2, "0")}:${minutes} ${ampm}`;
};
export const timeElapsed = (checkInTime, timeElapsedInHours) => {
const checkInDate = new Date( checkInTime.split( "T" )[ 0 ] );
const currentTime = new Date();
const timeDifference = currentTime - checkInDate;
const timeDifferenceInHours = timeDifference / (1000 * 60 * 60);
return timeDifferenceInHours >= timeElapsedInHours;
};
export const checkIfCurrentDate = (dateString) => {
const currentDate = new Date();
const inputDate = new Date(dateString);
currentDate.setHours(0, 0, 0, 0);
inputDate.setHours(0, 0, 0, 0);
return currentDate?.getTime() === inputDate?.getTime();
};
export const formatNumber = (num) => {
if (num == null || isNaN(num)) return "NA";
return Number.isInteger(num) ? num : num.toFixed(2);
};
export const formatUTCToLocalTime = (datetime, timeRequired = false) => {
return timeRequired
? moment.utc(datetime).local().format("DD MMM YYYY hh:mm A")
: moment.utc(datetime).local().format("DD MMM YYYY");
};
export const getCompletionPercentage = (completedWork, plannedWork)=> {
if (!plannedWork || plannedWork === 0) return 0;
const percentage = (completedWork / plannedWork) * 100;
const clamped = Math.min(Math.max(percentage, 0), 100);
return clamped.toFixed(2);
}
export const formatDate_DayMonth = (monthName, year) => {
if (!monthName || !year) return "";
try {
const shortMonth = monthName.substring(0, 3);
return `${shortMonth} ${year}`;
} catch {
return "";
}
};
export const getTenantStatus =(statusId)=>{
return ActiveTenant === statusId ? " bg-label-success":"bg-label-secondary"
}