hrms-mgt/src/utils/function.ts
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 6f40ee330c fix:function_calculateAge
2026-01-21 16:16:00 +07:00

62 lines
2.3 KiB
TypeScript

import moment from "moment";
/**
* คำนวณหน้าที่จะแสดงหลังจากลบข้อมูล
*
* @param page หน้าปัจจุบัน
* @param maxPage หน้าสุดท้าย
* @param currentPageItems จำนวนข้อมูลในหน้าปัจจุบัน
* @returns หน้าที่ควรแสดง
*/
export async function updateCurrentPage(
page: number,
maxPage: number,
total: number
) {
// ถ้าหน้าปัจจุบันไม่ใช่หน้าแรก และเป็นหน้าสุดท้าย และมีข้อมูลเหลือ 1 รายการ ให้กลับไปหน้าก่อนหน้า
if (page > 1 && page === maxPage && total === 1) {
return page - 1;
}
return page;
}
/**
* คำนวณปีงบประมาณ
*
* @param date วันที่ปัจจุบัน
* @returns ปีงบประมาณ
*/
export function calculateFiscalYear(date: Date) {
const month = date.getMonth() + 1;
return month >= 10 ? date.getFullYear() + 1 : date.getFullYear();
}
/**
* คำนวณอายุจากวันเกิด
* @param birthDate วันเกิด
* @returns อายุในรูปแบบ ปี เดือน วัน หรือ ข้อความ "อายุเกิน 60 ปี" หรือ null หากวันเกิดเป็น null
*/
export function calculateAge(birthDate: Date | null) {
if (!birthDate) return null;
// .startOf('day') จะเซ็ตเวลาเป็น 00:00:00.000 ของวันนั้นๆ
const birth = moment(birthDate).startOf("day");
const now = moment().startOf("day");
if (!birth.isValid()) return "Invalid Date";
// คราวนี้การลบกันจะสนแค่ "วันที่" เท่านั้น
const years = now.diff(birth, "years");
birth.add(years, "years");
const months = now.diff(birth, "months");
birth.add(months, "months");
const days = now.diff(birth, "days");
if (years >= 60) {
return "อายุเกิน 60 ปี";
}
return `${years} ปี ${months} เดือน ${days} วัน`;
}