Last active
March 31, 2018 09:23
-
-
Save navidanindya/3a99e6486533401db2bcbad2f9796e78 to your computer and use it in GitHub Desktop.
Simple format date parser for PHP (d-m-y or d-m-Y). [ Try out in sandbox: http://sandbox.onlinephpfunctions.com/code/b02657c7bfe827d7e3e20db231e07f3dd41de750 ]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This snippet does not validate dates. It's a simple parser for multiple CORRECT date formats. | |
// Some date inputs in different formats. Only accepts d-m-y or d-m-Y formats. | |
$dates = | |
array( | |
'19-1-1992', | |
'2/4/93', | |
'14-1-72', | |
'12-11-11', | |
'25,8,1993', | |
'8.8.92', | |
'20 4 00', | |
); | |
// Use this variable if wanting to convert different formats to one common format. | |
$commonFormat = 'd F Y'; | |
// String replace all separators for the date to hyphens. | |
$hyphener = | |
array( | |
'/', // Forward slash | |
',', // Comma | |
'.', // Dot | |
' ' // Space | |
); | |
for ($i = 0; $i < count($dates); $i++) { | |
$date = str_replace($hyphener, '-', $dates[$i]); | |
// Exploding only to check if year is two digit or four. | |
$explodedChecker = explode('-', $date); | |
// Different parsing for different year digits. | |
if (strlen($explodedChecker[2]) > 2) { | |
$date = DateTime::createFromFormat('d-m-Y', $date); | |
} else { | |
$date = DateTime::createFromFormat('d-m-y', $date); | |
} | |
$date = $date->format($commonFormat); | |
echo "Date ". ($i+1) .": " . $date . "\n"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment