PHP to convert Unix timestamp to Excel date format
<?php
// Function to convert Unix timestamp to Excel date format
function unixToExcelDate($unixTimestamp) {
// Adjust for Excel's epoch, which is January 1, 1900
$excelEpoch = 25569;
// Convert Unix timestamp to PHP timestamp
$phpTimestamp = $unixTimestamp;
// Calculate the number of days since Excel's epoch
$daysSinceEpoch = floor(($phpTimestamp - $excelEpoch) / 86400);
// Return the Excel date format
return $daysSinceEpoch + 1;
}
// Example usage
$unixTimestamp = 1640995200; // Timestamp for February 9, 2022
$excelDate = unixToExcelDate($unixTimestamp);
echo "Excel Date: " . $excelDate; // Output: 44657
Explanation:
- Function Definition: We define a function called
unixToExcelDate
that takes a Unix timestamp as input and converts it to Excel date format. - Excel Epoch: Excel uses a different epoch than Unix. Its epoch is January 1, 1900, which corresponds to the value 25569.
- PHP Timestamp Conversion: We convert the Unix timestamp to a PHP timestamp using the
$phpTimestamp
variable. - Days Since Epoch Calculation: We calculate the number of days since the Excel epoch using the formula
floor(($phpTimestamp - $excelEpoch) / 86400)
. This gives us the number of whole days that have passed since the Excel epoch. - Excel Date Format: To get the Excel date format, we add 1 to the number of days since the epoch. This gives us the Excel date, which represents the number of days that have passed since January 1, 1900, including the current day.
- Example Usage: We provide an example usage where we convert a given Unix timestamp to an Excel date and display the result.
Implementation:
To use this code, you can create a PHP file and paste the code into it. Then, you can call the unixToExcelDate
function with your own Unix timestamps to convert them to Excel date format.