Getting File Modified Date and Size in Multiple Formats
April 25, 2007 • 2 min read
This post demonstrates how to get a file’s last modified date and convert file sizes from bytes to KB, MB, and GB using PHP, JavaScript, and bash. We’ll also look at some improved approaches that handle edge cases and provide more robust solutions.
PHP Implementation
<?php
$file = 'image.jpg';
// File Last Modified Time
$filetime = filemtime($file); // displays in seconds since the Unix Epoch
echo date("M j, Y", $filetime); // displays as Feb 3, 2007
// File Sizes
$filesize = filesize($file); // displays in bytes
echo round(($filesize / 1024), 2); // bytes to KB
echo round(($filesize / 1048576), 2); // bytes to MB
echo round(($filesize / 1073741824), 2); // bytes to GB
?>
JavaScript Implementation
Node.js
const fs = require('fs');
const filename = 'image.jpg';
const stats = fs.statSync(filename);
// File Last Modified Time
const modifiedDate = stats.mtime;
console.log(modifiedDate.toLocaleDateString('en-US', {
year: 'numeric', month: 'short', day: 'numeric'
}));
// File Sizes
const filesize = stats.size; // displays in bytes
console.log((filesize / 1024).toFixed(2)); // bytes to KB
console.log((filesize / 1048576).toFixed(2)); // bytes to MB
console.log((filesize / 1073741824).toFixed(2)); // bytes to GB
Browser JavaScript
// Assuming you have a file input: <input type="file" onchange="getFileInfo(this.files[0])">
function getFileInfo(file) {
// File Last Modified Time
const modifiedDate = new Date(file.lastModified);
console.log(modifiedDate.toLocaleDateString('en-US', {
year: 'numeric', month: 'short', day: 'numeric'
}));
// File Sizes
const filesize = file.size; // displays in bytes
console.log((filesize / 1024).toFixed(2)); // bytes to KB
console.log((filesize / 1048576).toFixed(2)); // bytes to MB
console.log((filesize / 1073741824).toFixed(2)); // bytes to GB
}
Bash Implementation
#!/bin/bash
filename="image.jpg"
# File Last Modified Time
date -r "$filename" '+%b %d, %Y' # displays as Feb 3, 2007
# File Sizes
filesize=$(stat -c%s "$filename" 2>/dev/null || stat -f%z "$filename" 2>/dev/null)
echo "scale=2; $filesize / 1024" | bc # bytes to KB
echo "scale=2; $filesize / 1048576" | bc # bytes to MB
echo "scale=2; $filesize / 1073741824" | bc # bytes to GB
One-liner alternatives
# Get file modification date
stat -f "%Sm" -t "%b %d, %Y" image.jpg # macOS
stat -c "%y" image.jpg | cut -d' ' -f1 # Linux
# Get human-readable file size
ls -lh image.jpg | awk '{print $5}' # Shows auto-formatted size
du -h image.jpg | cut -f1 # Shows disk usage