JavaScript and PHP Date Formatting Functions with Validation
This page provides versatile and robust JavaScript and PHP functions to handle date formatting, validation, and localization with ease. Perfect for beginners and professionals alike. Extract weekday, month name, day and year
Contents
Demo Date Format
Select a date, click the Convert button, and view the date displayed in a human-readable format, including the day of the week and the full month name.
Extracted
- day : 13
- weekday : Friday
- monthName : December
- year : 2024
- timestamp : 1734048000000
- iso8601 : 2024-12-13T00:00:00.000Z
PHP Date Formatting Function
PHP developers can use this function to efficiently validate and format dates in 'YYYY-MM-DD' format. With support for localization and custom formats, this function is a perfect fit for any PHP-based project requiring robust date handling.
<?php
/**
* Formats a date string in YYYY-MM-DD format into a human-readable localized format.
* Example: "2024-12-04" -> "Wednesday, December 4, 2024"
*
* @param string $dateString The date in 'YYYY-MM-DD' format.
* @param array $config Configuration options:
* 'locale' (string) - Locale for formatting. (en-US (U.S. English) vs. fr-FR (French).
* 'format' (string) - Format style ('full', 'long', 'medium', 'short').
* @return array An associative array containing the formatted date and date parts.
* @throws InvalidArgumentException If the input date or config is invalid.
*/
function formatDate($dateString, $config = []) {
// Validate input format
$dateRegex = '/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/';
if (!preg_match($dateRegex, $dateString, $matches)) {
throw new InvalidArgumentException("Invalid date format: \"$dateString\". Expected 'YYYY-MM-DD'.");
}
// Extract components from the matched regex
list(, $yearStr, $monthStr, $dayStr) = $matches;
$year = (int)$yearStr;
$month = (int)$monthStr;
$day = (int)$dayStr;
// validate date components
if (!checkdate($month, $day, $year)) {
throw new InvalidArgumentException("Invalid date: \"$dateString\".");
}
// Default and merged configuration
$defaultConfig = [
'locale' => 'en-US',
'format' => 'full'
];
$mergedConfig = array_merge($defaultConfig, $config);
$supportedFormats = ['full', 'long', 'medium', 'short'];
if (!in_array($mergedConfig['format'], $supportedFormats)) {
throw new InvalidArgumentException("Invalid format: \"{$mergedConfig['format']}\". Supported: " . implode(', ', $supportedFormats) . ".");
}
// Create a DateTime object
$date = new DateTime($dateString, new DateTimeZone('UTC'));
// Use IntlDateFormatter for locale-aware formatting
$formatStyles = [
'full' => IntlDateFormatter::FULL,
'long' => IntlDateFormatter::LONG,
'medium' => IntlDateFormatter::MEDIUM,
'short' => IntlDateFormatter::SHORT,
];
$formatter = new IntlDateFormatter(
$mergedConfig['locale'],
$formatStyles[$mergedConfig['format']],
IntlDateFormatter::NONE,
'UTC'
);
if (!$formatter) {
throw new InvalidArgumentException("Locale \"{$mergedConfig['locale']}\" is not supported.");
}
$formattedDate = $formatter->format($date);
// Extract parts manually
$dayName = $date->format('j'); // Day of the month
$weekdayName = $date->format('l'); // Full weekday name
$monthName = $date->format('F'); // Full month name
// Return the result object
return [
'formatted' => $formattedDate,
'day' => $dayName,
'month' => $month,
'weekday' => $weekdayName,
'monthName' => $monthName,
'year' => $year,
'timestamp' => $date->getTimestamp(),
'iso8601' => $date->format(DateTime::ATOM),
];
}
?>
Note: The formatDate
function is designed to be compatible with PHP 5.6 and later. It uses the IntlDateFormatter
class from the intl
PHP extension.
PHP Example Usage
Here is how you can use the PHP code function:
<?php
try {
// Example 1: Default configuration
$result = formatDate('2024-12-09');
echo $result['formatted'] . PHP_EOL; // Output: Monday, December 9, 2024 (in en_US locale)
/**
print_r($result);
Array(
[formatted] => Monday, December 9, 2024
[day] => 9
[month] => 12
[weekday] => Monday
[monthName] => December
[year] => 2024
[timestamp] => 1733702400
[iso8601] => 2024-12-09T00:00:00+00:0000:00
)
**/
// Example 2: Custom locale and format
$example_2 = formatDate('2024-12-09', [
'locale' => 'fr_FR',
'format' => 'long'
]);
echo $example_2['formatted'] . PHP_EOL; // Output: 9 décembre 2024 (in French locale)
// Example 3: Medium format
$example_3 = formatDate('2024-12-09', [
'format' => 'medium'
]);
echo $example_3['formatted'] . PHP_EOL; // Output: Dec 9, 2024 (in en_US locale)
// Example 4: Short format
$example_4 = formatDate('2024-12-09', [
'format' => 'short'
]);
echo $example_4['formatted'] . PHP_EOL; // Output: 12/9/24 (in en_US locale)
// Example 5: Invalid date format
$example_5 = formatDate('2024-99-99'); // Throws Invalid date
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage() . PHP_EOL;
}
?>
JavaScript Date Formatting Function
The JavaScript function is designed to validate date strings in the 'YYYY-MM-DD' format, convert them into a human-readable format, and even support localization. It ensures input reliability and allows custom formatting options for ultimate flexibility.
/**
* Formats a date string and returns detailed information about it.
* @param {string} dateString - The date in 'YYYY-MM-DD' format.
* @param {Object} [config={}] - Configuration options.
* @param {string} [config.locale='en-US'] - Locale for formatting.
* @param {string} [config.format='full'] - Format style ('full', 'long', 'medium', 'short').
* @returns {Object} An object containing the formatted date and date parts.
* @throws {Error} If the input date or config is invalid.
*/
function formatDate(dateString, config = {}) {
// Helper function to validate date components
const isValidDate = (year, month, day) => {
const date = new Date(year, month - 1, day);
return date.getFullYear() === year &&
date.getMonth() === month - 1 &&
date.getDate() === day;
};
// Validate input format
const dateRegex = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
const match = dateString.match(dateRegex);
if (!match) {
throw new Error(`Invalid date format: "${dateString}". Expected 'YYYY-MM-DD'.`);
}
// Extract components from the matched regex
const [, yearStr, monthStr, dayStr] = match;
const year = parseInt(yearStr, 10);
const month = parseInt(monthStr, 10);
const day = parseInt(dayStr, 10);
if (!isValidDate(year, month, day)) {
throw new Error(`Invalid date: "${dateString}".`);
}
// Default and merged configuration
const defaultConfig = { locale: 'en-US', format: 'full' };
const mergedConfig = { ...defaultConfig, ...config };
const supportedFormats = ['full', 'long', 'medium', 'short'];
if (!supportedFormats.includes(mergedConfig.format)) {
throw new Error(`Invalid format: "${mergedConfig.format}". Supported: ${supportedFormats.join(', ')}.`);
}
// Create Intl.DateTimeFormat instances
const dateFormatter = new Intl.DateTimeFormat(mergedConfig.locale, {
dateStyle: mergedConfig.format,
timeZone: 'UTC'
});
const fullFormatter = new Intl.DateTimeFormat(mergedConfig.locale, {
dateStyle: 'full',
timeZone: 'UTC'
});
// Create date object
const date = new Date(dateString);
// Format the date and extract parts
const formattedDate = dateFormatter.format(date);
const parts = fullFormatter.formatToParts(date);
// Safely extract parts
const findPart = (type) => parts.find(part => part.type === type)?.value || '';
const dayName = findPart('day');
const weekdayName = findPart('weekday');
const monthName = findPart('month');
// Return the result object
return {
formatted: formattedDate,
day: dayName,
weekday: weekdayName,
monthName,
year,
month,
timestamp: date.getTime(),
iso8601: date.toISOString(),
};
}
JavaScript Example Usage
// Example usages
try {
// Example 1: Default configuration
const result = formatDate('2024-12-10');
console.log(result.formatted); // Tuesday, December 10, 2024
// console.log(result.day); // 10
// console.log(result.month); // 12
// console.log(result.year); // 2024
// console.log(result.weekday); // Tuesday
// console.log(result.monthName); // December
// console.log(result.timestamp); // 1733788800000
// console.log(result.iso8601); // 2024-12-10T00:00:00.000Z
// Example 2: Custom locale
const example_2 = formatDate('2024-12-31', {
locale: 'fr-FR',
});
console.log(example_2.formatted); // mardi 31 décembre 2024
// Example 3: Medium format
const example_3 = formatDate('2024-12-31', {
locale: 'en-US',
format: 'medium'
});
console.log(example_3.formatted); // Dec 31, 2024
// Example 4: Short format
const example_4 = formatDate('2024-12-31', {
format: 'short'
});
console.log(example_4.formatted); // 12/31/24
// Example 5: Invalid date format
const example_5 = formatDate('2023-02-29', {
format: 'full'
});
console.log(example_5.formatted); // Error: Invalid date: "2023-02-29".
} catch (error) {
console.error("Example 5 Error:", error.message);
}
Function Features
- Input Validation
- Strict date format validation (YYYY-MM-DD)
- Comprehensive date component checking
- Prevents invalid dates (e.g., February 30)
- Configuration Options
- Customizable locale (default: en-US)
- Multiple date format styles (full, long, medium, short)
- Output Information
- Internationalized formatted date string
- Extracted date components (day, weekday, month, year)
- Unix timestamp
- ISO8601 date format
- Error Handling
- Detailed error messages for invalid inputs
- Specific InvalidArgumentException types for different error scenarios
JavaScript Extracts Day, Month, And Year From a Given Date
Here is the a JavaScript function to extract the day, month, and year from a given date.
function extractDateParts(date) {
// If no date is provided, use current date
const targetDate = date ? new Date(date) : new Date();
return {
day: targetDate.getDate(),
month: targetDate.getMonth() + 1, // Note: Months are 0-indexed
year: targetDate.getFullYear()
};
}
Usage Date Extracts
// Example usages
console.log(extractDateParts()); // Current date
console.log(extractDateParts('2024-05-15')); // {day: 15, month: 5, year: 2024}