1
0
forked from Yara724/api
Files
yara724-api/src/helpers/date-jalali.ts

60 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Converts an ISO date string or Date to Jalali (Persian) date and time.
* @param input - ISO date string (e.g. 2026-02-08T13:51:20.747+00:00) or Date
* @returns Tuple [dateStr, timeStr] e.g. ['1404/11/24', '13:37']
*/
export function toJalaliDateAndTime(
input: string | Date,
): [string, string] {
const d = new Date(input);
const dateStr = toJalaliDate(d);
const timeStr = toJalaliTime(d);
return [dateStr, timeStr];
}
/**
* Converts a Date to Jalali date string (e.g. 1404/11/24).
*/
export function toJalaliDate(d: Date): string {
const persianDate = d.toLocaleDateString("fa-IR", {
year: "numeric",
month: "2-digit",
day: "2-digit",
});
return persianDigitsToEnglish(persianDate, "/");
}
/**
* Converts a Date to 24h time string (e.g. 13:37).
*/
export function toJalaliTime(d: Date): string {
const hours = d.getHours().toString().padStart(2, "0");
const minutes = d.getMinutes().toString().padStart(2, "0");
return `${hours}:${minutes}`;
}
const PERSIAN_TO_ENGLISH: Record<string, string> = {
"۰": "0",
"۱": "1",
"۲": "2",
"۳": "3",
"۴": "4",
"۵": "5",
"۶": "6",
"۷": "7",
"۸": "8",
"۹": "9",
};
function persianDigitsToEnglish(str: string, separator: string): string {
return str
.split(separator)
.map((part) =>
part
.split("")
.map((char) => PERSIAN_TO_ENGLISH[char] ?? char)
.join(""),
)
.join("/");
}