التواريخ في JavaScript
تستخدم JavaScript كائن Date للعمل مع التواريخ والأوقات. فكّر فيه كـ ساعة رقمية — يعرض الوقت الحالي، يتيح لك تعيين أي لحظة، ويمكنه حساب الفرق بين وقتيين.
📖 ملخص
إنشاء كائنات Date
أربع طرق شائعة لإنشاء Date:
<script>
console.log(new Date()); // التاريخ والوقت الحاليان
console.log(new Date("2025-06-19")); // سلسلة تاريخ
console.log(new Date(2025, 5, 19, 10, 30, 0)); // سنة، شهر، يوم، ساعات، دقائق، ثواني
console.log(new Date(1718764800000)); // طابع زمني (ميلي ثانية)
</script>
مشكلة كبيرة: الأشهر تبدأ من الصفر! 0 = يناير، 11 = ديسمبر. في new Date(2025, 5, 19)، الرقم 5 يعني يونيو وليس مايو. هذه arguably أكثر قرار تصميم انتُقد في كائن Date — على الإطلاق.
الحصول على التاريخ والوقت
| الطريقة | تُرجع | ملاحظة |
|---|---|---|
getFullYear() |
سنة بأربعة أرقام | لا تستخدم getYear() — مهملة |
getMonth() |
0–11 | أضف 1 للشهر الفعلي |
getDate() |
1–31 | يوم الشهر |
getDay() |
0–6 | 0 = الأحد وليس الاثنين! |
getHours() |
0–23 | — |
getMinutes() |
0–59 | — |
getSeconds() |
0–59 | — |
getDay() تُرجع يوم الأسبوع وليس يوم الشهر — استخدم getDate() لذلك. المبتدئون كثيراً ما يخلطون بينهما.
تعيين التاريخ والوقت
توجد مجموعة مطابقة من طرق set: setFullYear()، setMonth()، setDate()، setHours()، setMinutes()، setSeconds(). القيم تتدحرج تلقائياً عند التعيين:
<script>
const d = new Date(2025, 5, 19);
d.setDate(32); // تصبح تلقائياً 2 يوليو
console.log(d.toLocaleDateString());
</script>
تنسيق التواريخ
| الطريقة | مثال المخرجات |
|---|---|
toLocaleDateString() |
"6/19/2025" |
toLocaleTimeString() |
"10:30:00 AM" |
toLocaleString() |
"6/19/2025, 10:30:00 AM" |
هذه الطرق تنسق تلقائياً بناءً على إعدادات_locale للمتصفح.
الطوابع الزمنية وحساب فروقات الوقت
الطابع الزمني هو عدد المليلي ثواني المنقضية منذ 1 يناير 1970 00:00:00 UTC.
<script>
console.log(Date.now()); // الحصول على الطابع الزمني الحالي
console.log(new Date().getTime()); // نفس ما فوق
</script>
النهج الأساسي لحساب فروقات الوقت: طرح طابعين زمنيين للحصول على الفرق بالمليلي ثانية، ثم التحويل:
<script>
const start = Date.now();
for (let i = 0; i < 1000000; i++) {} // محاكاة بعض العمليات
const end = Date.now();
const diff = end - start; // ميلي ثانية
const diffSeconds = diff / 1000; // ثواني
console.log("الوقت المنقضي: " + diff + "مللي ثانية (" + diffSeconds + " ثانية)");
</script>
مثال: عرض التاريخ والوقت الحاليين
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>التاريخ والوقت الحاليان</title>
<style>
body { font-family: sans-serif; padding: 20px; text-align: center; }
.clock { display: inline-block; padding: 24px 40px; background: #1a1a2e; color: #e0e0e0; border-radius: 12px; }
.time { font-size: 48px; font-weight: bold; color: #00d4ff; font-family: monospace; direction: ltr; }
.date { font-size: 20px; margin-top: 8px; color: #a0a0c0; }
</style>
</head>
<body>
<h2>ساعة مباشرة</h2>
<div class="clock">
<div class="time" id="time">--:--:--</div>
<div class="date" id="date">----/--/--</div>
</div>
<script>
function updateClock() {
const now = new Date();
const h = String(now.getHours()).padStart(2, "0");
const m = String(now.getMinutes()).padStart(2, "0");
const s = String(now.getSeconds()).padStart(2, "0");
document.getElementById("time").textContent = `${h}:${m}:${s}`;
const y = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const d = String(now.getDate()).padStart(2, "0");
const weekdays = ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"];
document.getElementById("date").textContent = `${y}-${month}-${d} ${weekdays[now.getDay()]}`;
}
updateClock();
setInterval(updateClock, 1000);
</script>
</body>
</html>
مثال: تفاصيل معلومات التاريخ
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>معلومات التاريخ</title>
<style>
body { font-family: sans-serif; padding: 20px; }
table { border-collapse: collapse; margin: 16px 0; direction: ltr; }
td, th { border: 1px solid #ddd; padding: 10px 16px; text-align: left; }
th { background: #4a90d9; color: #fff; }
.note { background: #fff8e1; padding: 12px; border-radius: 6px; border-right: 4px solid #f0ad4e; margin: 16px 0; }
</style>
</head>
<body>
<h2>قيم إرجاع طرق كائن Date</h2>
<div id="output"></div>
<script>
const now = new Date();
const data = [
["getFullYear()", now.getFullYear(), "سنة بأربعة أرقام"],
["getMonth()", now.getMonth(), "0-11 (أضف 1 للشهر الفعلي)"],
["getDate()", now.getDate(), "1-31 (يوم الشهر)"],
["getDay()", now.getDay(), "0-6 (0 = الأحد)"],
["getHours()", now.getHours(), "0-23"],
["getMinutes()", now.getMinutes(), "0-59"],
["getSeconds()", now.getSeconds(), "0-59"],
["getTime()", now.getTime(), "طابع زمني (مليلي ثانية)"],
];
document.getElementById("output").innerHTML = `
<table>
<tr><th>الطريقة</th><th>قيمة الإرجاع</th><th>الوصف</th></tr>
${data.map(r => `<tr><td><code>${r[0]}</code></td><td>${r[1]}</td><td>${r[2]}</td></tr>`).join("")}
</table>
<div class="note">
<strong>الأشهر تبدأ من الصفر</strong>: getMonth() تُرجع ${now.getMonth()}، لكن الشهر الفعلي هو ${now.getMonth()+1}.
<strong>getDay() هو يوم الأسبوع</strong>: تُرجع ${now.getDay()} (${["الأحد","الاثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"][now.getDay()]}), وليس التاريخ!
</div>
`;
</script>
</body>
</html>
مثال: مؤقت تنازلي
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>عد تنازلي</title>
<style>
body { font-family: sans-serif; padding: 20px; text-align: center; }
.countdown { display: inline-block; padding: 24px; background: linear-gradient(135deg, #667eea, #764ba2); color: #fff; border-radius: 12px; margin: 16px 0; }
.countdown h3 { margin: 0 0 12px; font-size: 18px; }
.timer { display: flex; gap: 16px; justify-content: center; direction: ltr; }
.unit { text-align: center; }
.number { font-size: 40px; font-weight: bold; font-family: monospace; }
.label { font-size: 12px; opacity: 0.8; }
.input-row { margin: 16px 0; }
input { padding: 8px 12px; font-size: 16px; border: 2px solid #ccc; border-radius: 6px; }
button { padding: 8px 20px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; background: #4a90d9; color: #fff; }
button:hover { background: #357abd; }
</style>
</head>
<body>
<h2>عد تنازلي حتى التاريخ المستهدف</h2>
<div class="input-row">
<input type="datetime-local" id="target" />
<button id="startBtn">ابدأ العد التنازلي</button>
</div>
<div class="countdown" id="countdown" style="display:none;">
<h3 id="targetLabel">الوقت المتبقي</h3>
<div class="timer">
<div class="unit"><div class="number" id="days">0</div><div class="label">أيام</div></div>
<div class="unit"><div class="number" id="hours">0</div><div class="label">ساعات</div></div>
<div class="unit"><div class="number" id="minutes">0</div><div class="label">دقائق</div></div>
<div class="unit"><div class="number" id="seconds">0</div><div class="label">ثواني</div></div>
</div>
</div>
<script>
const defaultTarget = new Date();
defaultTarget.setDate(defaultTarget.getDate() + 7);
const dateStr = defaultTarget.toISOString().slice(0, 16);
document.getElementById("target").value = dateStr;
let timer = null;
document.getElementById("startBtn").addEventListener("click", function() {
const target = new Date(document.getElementById("target").value);
if (isNaN(target.getTime())) {
alert("الرجاء اختيار تاريخ ووقت صالحين");
return;
}
document.getElementById("countdown").style.display = "inline-block";
document.getElementById("targetLabel").textContent =
`الوقت حتى ${target.toLocaleString()}`;
if (timer) clearInterval(timer);
function update() {
const now = Date.now();
const diff = target.getTime() - now;
if (diff <= 0) {
document.getElementById("days").textContent = "0";
document.getElementById("hours").textContent = "0";
document.getElementById("minutes").textContent = "0";
document.getElementById("seconds").textContent = "0";
document.getElementById("targetLabel").textContent = "انتهى الوقت!";
clearInterval(timer);
return;
}
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
document.getElementById("days").textContent = days;
document.getElementById("hours").textContent = String(hours).padStart(2, "0");
document.getElementById("minutes").textContent = String(minutes).padStart(2, "0");
document.getElementById("seconds").textContent = String(seconds).padStart(2, "0");
}
update();
timer = setInterval(update, 1000);
});
</script>
</body>
</html>
مثال: حاسبة فرق التاريخ
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<title>فرق التاريخ</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.calc { max-width: 500px; margin: 16px auto; }
.row { margin: 12px 0; }
label { display: inline-block; width: 100px; font-weight: bold; }
input { padding: 8px 12px; font-size: 16px; border: 2px solid #ccc; border-radius: 6px; }
button { padding: 8px 20px; font-size: 16px; border: none; border-radius: 6px; cursor: pointer; background: #5cb85c; color: #fff; margin-top: 8px; }
button:hover { background: #449d44; }
.result { margin-top: 16px; padding: 16px; background: #f0f7ff; border-radius: 8px; border: 2px solid #4a90d9; }
.result div { margin: 4px 0; }
</style>
</head>
<body>
<h2 style="text-align:center;">حاسبة فرق التاريخ</h2>
<div class="calc">
<div class="row">
<label>تاريخ البداية:</label>
<input type="date" id="start" />
</div>
<div class="row">
<label>تاريخ النهاية:</label>
<input type="date" id="end" />
</div>
<div style="text-align:center;">
<button id="calcBtn">احسب</button>
</div>
<div class="result" id="result" style="display:none;"></div>
</div>
<script>
const today = new Date();
const lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);
document.getElementById("start").value = lastMonth.toISOString().slice(0, 10);
document.getElementById("end").value = today.toISOString().slice(0, 10);
document.getElementById("calcBtn").addEventListener("click", function() {
const start = new Date(document.getElementById("start").value);
const end = new Date(document.getElementById("end").value);
if (isNaN(start.getTime()) || isNaN(end.getTime())) {
alert("الرجاء اختيار تواريخ صالحة");
return;
}
const diffMs = Math.abs(end - start);
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffMinutes = Math.floor(diffMs / (1000 * 60));
const diffWeeks = Math.floor(diffDays / 7);
document.getElementById("result").style.display = "block";
document.getElementById("result").innerHTML = `
<div><strong>أيام:</strong> ${diffDays}</div>
<div><strong>ساعات:</strong> ${diffHours}</div>
<div><strong>دقائق:</strong> ${diffMinutes}</div>
<div><strong>تقريباً:</strong> ${diffWeeks} أسابيع و ${diffDays % 7} أيام</div>
`;
});
</script>
</body>
</html>
❓ أسئلة شائعة
getMonth() يتطلب إضافة 1؟Date في Java صُممت بهذه الطريقة، ورثت JavaScript تلك "التقليد". الجميع يتفق أن التصميم سخيف، لكن لا يمكن تغييره — كثير من الكود الحالي يعتمد على هذا السلوك. فقط احفظه.new Date("2025-06-19") و new Date(2025, 5, 19)؟📝 تمارين
- اكتب دالة
formatDate(date)تُعيد سلسلة بالشكل"YYYY-MM-DD (يوم الأسبوع)". تأكد أن الأشهر والأيام تت padding بأصفار. - اكتب دالة
getAge(birthday)تستقبل سلسلة تاريخ (مثل "2000-03-15") وتُعيد العمر الحالي بالسنوات الكاملة. - ابني ميزة "وقت سابق": بتواريخ تاريخ الماضي، اعرض "منذ X سنوات، X أشهر، X أيام" أو "منذ X أيام" أو "منذ X ساعات" — مع اختيار التنسيق المناسب تلقائياً بناءً على فرق الوقت.



