Last active
October 1, 2015 11:08
-
-
Save ethaizone/6696213e9eafdcc23f14 to your computer and use it in GitHub Desktop.
Date in Thai
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 | |
/** | |
* Date function for Thai | |
* Lazy code version. | |
* | |
* Don't remove copyright. | |
* | |
* @author Nimit Suwannagate <ethaizone@hotmail.com> | |
*/ | |
function dateTH($format = "Y-m-d H:i:s", $baseTime = null) | |
{ | |
// format from momentjs | |
$customFormat = [ | |
'day' => [ | |
'D' => 'อา._จ._อ._พ._พฤ._ศ._ส.', | |
'l' => 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์', | |
], | |
'month' => [ | |
'M' => 'มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา', | |
'F' => 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม', | |
], | |
'year' => [ | |
'Y' => function($year) | |
{ | |
return 'พ.ศ.'.($year+543); | |
} | |
] | |
]; | |
return dateWithCustomFormat($format, $baseTime, $customFormat); | |
} | |
function dateWithCustomFormat($format = "Y-m-d H:i:s", $baseTime = null, $customFormat) | |
{ | |
if (! $baseTime) { | |
$baseTime = time(); | |
} | |
if (! is_numeric($baseTime)) { | |
$baseTime = strtotime($baseTime); | |
} | |
$result = null; | |
// Backup format that will change | |
$index = 1; | |
foreach($customFormat as $group => $list) { | |
foreach($list as $custom => $data) { | |
$format = str_replace("\\".$custom, "[::tmp::]", $format); // backup escape | |
$format = str_replace($custom, "[::".$index."::]", $format); // make custom format to special format | |
$format = str_replace("[::tmp::]", "\\".$custom, $format); // restore escape | |
$index++; | |
} | |
} | |
// create first result from date() | |
$result = date($format, $baseTime); | |
// replace another result with custom lang | |
$index = 1; | |
foreach($customFormat as $group => $list) { | |
foreach($list as $custom => $data) { | |
$res = "$custom"; | |
$ingredent = null; | |
switch ($group) { | |
case 'year': | |
$ingredent = date("Y", $baseTime); | |
break; | |
case 'day': | |
$ingredent = date("w", $baseTime); | |
break; | |
case 'month': | |
$ingredent = date("n", $baseTime)-1; | |
break; | |
} | |
if (is_callable($data)) | |
{ | |
$res = $data($ingredent); | |
} | |
else | |
{ | |
$data = explode("_", $data); | |
if (!empty($data[$ingredent])) | |
{ | |
$res = $data[$ingredent]; | |
} | |
} | |
$result = str_replace("[::".$index."::]", $res, $result); | |
$index++; | |
} | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment