-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
349 lines (296 loc) · 12 KB
/
script.js
File metadata and controls
349 lines (296 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
function gregorianToPersian(gDate) {
const gy = gDate.getFullYear();
const gm = gDate.getMonth() + 1;
const gd = gDate.getDate();
const gDayOffsets = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
const gy2 = gm > 2 ? gy + 1 : gy;
let days = 355666 + (365 * gy)
+ Math.floor((gy2 + 3) / 4)
- Math.floor((gy2 + 99) / 100)
+ Math.floor((gy2 + 399) / 400)
+ gd
+ gDayOffsets[gm - 1];
let jy = -1595 + (33 * Math.floor(days / 12053));
days %= 12053;
jy += 4 * Math.floor(days / 1461);
days %= 1461;
if (days > 365) {
jy += Math.floor((days - 1) / 365);
days = (days - 1) % 365;
}
let jm;
let jd;
if (days < 186) {
jm = 1 + Math.floor(days / 31);
jd = 1 + (days % 31);
} else {
jm = 7 + Math.floor((days - 186) / 30);
jd = 1 + ((days - 186) % 30);
}
return { year: jy, month: jm, date: jd };
}
function persianToGregorian(jy, jm, jd) {
jy += 1595;
let days = -355668
+ (365 * jy)
+ (Math.floor(jy / 33) * 8)
+ Math.floor(((jy % 33) + 3) / 4)
+ jd
+ (jm < 7 ? (jm - 1) * 31 : ((jm - 7) * 30) + 186);
let gy = 400 * Math.floor(days / 146097);
days %= 146097;
if (days > 36524) {
gy += 100 * Math.floor(--days / 36524);
days %= 36524;
if (days >= 365) {
days++;
}
}
gy += 4 * Math.floor(days / 1461);
days %= 1461;
if (days > 365) {
gy += Math.floor((days - 1) / 365);
days = (days - 1) % 365;
}
let gd = days + 1;
const gregorianMonthDays = [
0,
31,
((gy % 4 === 0 && gy % 100 !== 0) || (gy % 400 === 0)) ? 29 : 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
let gm = 0;
for (; gm < 13 && gd > gregorianMonthDays[gm]; gm++) {
gd -= gregorianMonthDays[gm];
}
return new Date(gy, gm - 1, gd);
}
function gregorianToHijri(gDate) {
const year = gDate.getFullYear();
const month = gDate.getMonth() + 1;
const day = gDate.getDate();
const jd = Math.floor((1461 * (year + 4800 + Math.floor((month - 14) / 12))) / 4) +
Math.floor((367 * (month - 2 - 12 * Math.floor((month - 14) / 12))) / 12) -
Math.floor((3 * Math.floor((year + 4900 + Math.floor((month - 14) / 12)) / 100)) / 4) +
day - 32075;
let l = jd - 1948440 + 10632;
const n = Math.floor((l - 1) / 10631);
l = l - (10631 * n) + 354;
const j = (Math.floor((10985 - l) / 5316)) * (Math.floor((50 * l) / 17719))
+ (Math.floor(l / 5670)) * (Math.floor((43 * l) / 15238));
l = l
- (Math.floor((30 - j) / 15)) * (Math.floor((17719 * j) / 50))
- (Math.floor(j / 16)) * (Math.floor((15238 * j) / 43))
+ 29;
const hm = Math.floor((24 * l) / 709);
const hd = l - Math.floor((709 * hm) / 24);
const hy = 30 * n + j - 30;
return { year: hy, month: hm, date: hd };
}
function hijriToGregorian(hy, hm, hd) {
let jd = Math.floor((11 * hy + 3) / 30) + 354 * hy + 30 * hm - Math.floor((hm - 1) / 2) + hd + 1948440 - 385;
let l = jd + 68569;
let n = Math.floor((4 * l) / 146097);
l = l - Math.floor((146097 * n + 3) / 4);
let i = Math.floor((4000 * (l + 1)) / 1461001);
l = l - Math.floor((1461 * i) / 4) + 31;
let j = Math.floor((80 * l) / 2447);
let d = l - Math.floor((2447 * j) / 80);
l = Math.floor(j / 11);
let m = j + 2 - 12 * l;
let y = 100 * (n - 49) + i + l;
return new Date(y, m - 1, d);
}
const dayNamesGreg = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
const dayNamesPers = ['یکشنبه','دوشنبه','سهشنبه','چهارشنبه','پنجشنبه','جمعه','شنبه'];
const dayNamesHijri = ['الأحد','الاثنين','الثلاثاء','الأربعاء','الخميس','الجمعة','السبت'];
const persianMonthNames = {
en: ["Farvardin","Ordibehesht","Khordad","Tir","Mordad","Shahrivar","Mehr","Aban","Azar","Dey","Bahman","Esfand"],
fa: ["فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"]
};
const hijriMonthNames = {
en: ["Muharram","Safar","Rabi' al-Awwal","Rabi' al-Thani","Jumada al-Awwal","Jumada al-Thani","Rajab","Sha'ban","Ramadan","Shawwal","Dhu al-Qa'dah","Dhu al-Hijjah"],
fa: ["محرم","صفر","ربيع الأول","ربيع الثاني","جمادى الأولى","جمادى الثانية","رجب","شعبان","رمضان","شوال","ذو القعدة","ذو الحجة"]
};
const translations = {
en: {
pageTitle: "Date Converter",
gregTitle: "Gregorian (Miladi)",
persianTitle: "Persian (Jalali)",
hijriTitle: "Hijri (Qamari)",
todayBtn: "Set to Today",
footerDescription: "Universal date converter for Gregorian, Persian, and Hijri calendars.",
repoLabel: "GitHub Repository",
seoTitle: "TimeBridge | Universal Date Converter",
seoDescription: "TimeBridge: Universal date converter for Gregorian, Persian, and Hijri calendars."
},
fa: {
pageTitle: "تبدیل تاریخها",
gregTitle: "میلادی",
persianTitle: "هجری شمسی",
hijriTitle: "هجری قمری",
todayBtn: "امروز",
footerDescription: "تبدیلگر تاریخ برای تقویمهای میلادی، شمسی و قمری.",
repoLabel: "مخزن گیتهاب",
seoTitle: "TimeBridge | تبدیل تاریخها",
seoDescription: "TimeBridge: تبدیلگر تاریخ برای تقویمهای میلادی، شمسی و قمری."
}
};
let currentLang = 'en';
const byId = (id) => document.getElementById(id);
const gregInput = byId('gregorian');
const persianInput = byId('persian');
const hijriInput = byId('hijri');
const gregDisplay = byId('gregorian-display');
const persianDisplay = byId('persian-display');
const hijriDisplay = byId('hijri-display');
const themeBtn = byId('theme-btn');
const langButtons = { en: byId('lang-en-btn'), fa: byId('lang-fa-btn') };
const textElements = {
pageTitle: byId('page-title'),
gregTitle: byId('greg-title'),
persianTitle: byId('persian-title'),
hijriTitle: byId('hijri-title'),
todayBtn: byId('today-btn-text'),
footerDescription: byId('footer-description'),
repoLabel: byId('repo-link')
};
const digitMaps = {
fa: ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'],
ar: ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩']
};
function pad(n) { return n < 10 ? '0' + n : n; }
function convertDigits(value, digits) {
return String(value).replace(/\d/g, (digit) => digits[Number(digit)]);
}
function localizeNumber(value, locale) {
return locale ? convertDigits(value, digitMaps[locale]) : String(value);
}
function normalizeDigits(value) {
return String(value)
.replace(/[۰-۹]/g, (digit) => String(digit.charCodeAt(0) - 1728))
.replace(/[٠-٩]/g, (digit) => String(digit.charCodeAt(0) - 1632));
}
function normalizeTextInputValue(input) {
const normalizedValue = normalizeDigits(input.value);
if (input.value !== normalizedValue) input.value = normalizedValue;
return normalizedValue;
}
function localizeInputValue(input, locale) {
if (!locale || currentLang !== 'fa') return;
const start = input.selectionStart;
const end = input.selectionEnd;
const localizedValue = localizeNumber(normalizeDigits(input.value), locale);
if (input.value !== localizedValue) {
input.value = localizedValue;
if (start !== null && end !== null) input.setSelectionRange(start, end);
}
}
function getCurrentDate() {
return gregInput.value ? new Date(gregInput.value) : new Date();
}
function formatCalendarText(date, monthName, weekday, locale) {
const year = localizeNumber(date.year, locale);
const day = localizeNumber(date.date, locale);
return currentLang === 'fa'
? `${day} <span class="font-semibold">${monthName}</span> ${year}`
: `<span class="font-semibold">${monthName}</span> ${day}, ${year}`;
}
function setCalendarOutput(input, display, date, monthNames, weekday, locale) {
const rawValue = `${date.year}/${pad(date.month)}/${pad(date.date)}`;
input.value = locale ? localizeNumber(rawValue, locale) : rawValue;
display.innerHTML = `${formatCalendarText(date, monthNames[currentLang][date.month - 1], weekday, locale)} <span class="text-gray-500 dark:text-gray-400 mx-2">•</span> ${weekday}`;
}
function updateCalendars(date) {
if (!date || isNaN(date.getTime())) return;
const weekdayIndex = date.getDay();
gregInput.value = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
gregDisplay.textContent = `${dayNamesGreg[weekdayIndex]}, ${date.toLocaleString('en-US', { month: 'short' })} ${date.getDate()}, ${date.getFullYear()}`;
setCalendarOutput(
persianInput,
persianDisplay,
gregorianToPersian(date),
persianMonthNames,
currentLang === 'fa' ? dayNamesPers[weekdayIndex] : dayNamesGreg[weekdayIndex],
currentLang === 'fa' ? 'fa' : null
);
setCalendarOutput(
hijriInput,
hijriDisplay,
gregorianToHijri(date),
hijriMonthNames,
currentLang === 'fa' ? dayNamesHijri[weekdayIndex] : dayNamesGreg[weekdayIndex],
currentLang === 'fa' ? 'ar' : null
);
}
function handleTextCalendarInput(input, converter, locale) {
const normalizedValue = normalizeTextInputValue(input);
localizeInputValue(input, locale);
const parts = normalizedValue.split('/');
if (parts.length !== 3) return;
const [year, month, day] = parts.map(Number);
if (year && month && day) updateCalendars(converter(year, month, day));
}
function switchLanguage(lang) {
currentLang = lang;
localStorage.setItem('lang', lang);
Object.entries(textElements).forEach(([key, element]) => {
element.textContent = translations[lang][key];
});
Object.entries(langButtons).forEach(([key, button]) => {
button.classList.toggle('bg-blue-600', key === lang);
button.classList.toggle('text-white', key === lang);
});
document.documentElement.dir = lang === 'fa' ? 'rtl' : 'ltr';
document.documentElement.lang = lang;
document.title = translations[lang].seoTitle;
byId('repo-link').textContent = translations[lang].repoLabel;
const metaDescription = document.querySelector('meta[name="description"]');
const ogTitle = document.querySelector('meta[property="og:title"]');
const ogDescription = document.querySelector('meta[property="og:description"]');
const twitterTitle = document.querySelector('meta[name="twitter:title"]');
const twitterDescription = document.querySelector('meta[name="twitter:description"]');
const ogLocale = document.querySelector('meta[property="og:locale"]');
metaDescription?.setAttribute('content', translations[lang].seoDescription);
ogTitle?.setAttribute('content', translations[lang].seoTitle);
ogDescription?.setAttribute('content', translations[lang].seoDescription);
twitterTitle?.setAttribute('content', translations[lang].seoTitle);
twitterDescription?.setAttribute('content', translations[lang].seoDescription);
ogLocale?.setAttribute('content', lang === 'fa' ? 'fa_IR' : 'en_US');
updateCalendars(getCurrentDate());
}
function toggleTheme() {
const isDark = document.documentElement.classList.toggle('dark');
themeBtn.textContent = isDark ? '🌙' : '🌞';
localStorage.setItem('theme', isDark ? 'dark' : 'light');
}
function setToToday() {
updateCalendars(new Date());
}
function init() {
const savedTheme = localStorage.getItem('theme');
const isDark = savedTheme ? savedTheme === 'dark' : window.matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.classList.toggle('dark', isDark);
themeBtn.textContent = isDark ? '🌙' : '🌞';
switchLanguage(localStorage.getItem('lang') || 'en');
updateCalendars(new Date());
}
gregInput.addEventListener('input', () => {
if (gregInput.value) updateCalendars(new Date(gregInput.value));
});
persianInput.addEventListener('input', () => handleTextCalendarInput(persianInput, persianToGregorian, 'fa'));
hijriInput.addEventListener('input', () => handleTextCalendarInput(hijriInput, hijriToGregorian, 'ar'));
langButtons.en.addEventListener('click', () => switchLanguage('en'));
langButtons.fa.addEventListener('click', () => switchLanguage('fa'));
themeBtn.addEventListener('click', toggleTheme);
byId('today-btn').addEventListener('click', setToToday);
window.addEventListener('load', init);