แปลง DD/MM/YYYY เป็น YYYY-MM
15/01/2025 → 2025-01
ตัวแปลงด่วน
→
2025-01
วิธีแปลง DD/MM/YYYY เป็น YYYY-MM
การแปลงจาก DD/MM/YYYY เป็น YYYY-MM ต้องจัดเรียงส่วนประกอบวันที่ใหม่:
จาก
DD/MM/YYYY
15/01/2025
เป็น
YYYY-MM
2025-01
1
ระบุส่วนประกอบ
ในรูปแบบ DD/MM/YYYY: Day-Month-Year format commonly used in Europe, Asia, and most of the world
2
จัดเรียงใหม่
จัดลำดับใหม่ให้ตรงกับรูปแบบ YYYY-MM: Year-month format following ISO 8601, ideal for file naming and sorting
3
ปรับตัวคั่น
เปลี่ยนตัวคั่นจาก "/" เป็น "-" หากจำเป็น
ตัวอย่างโค้ด
JavaScript
// แปลง DD/MM/YYYY เป็น YYYY-MM
function convertDate(dateStr) {
// แปลง DD/MM/YYYY
const parts = dateStr.split('/');
const [day, month, year] = parts;
// จัดรูปแบบเป็น YYYY-MM
return `${year}-${month}-${day}`;
}
console.log(convertDate('15/01/2025')); // 2025-01
Python
from datetime import datetime
# แปลง DD/MM/YYYY เป็น YYYY-MM
date_str = '15/01/2025'
date = datetime.strptime(date_str, '%d/%m/%Y')
result = date.strftime('%Y-%m-%d')
print(result) # 2025-01