SortByDateField

The Contact Form DB SortByDateField class.

Defined (1)

The class is defined in the following location(s).

/SortByDateField.php  
  1. class SortByDateField extends SortTransform { 
  2.  
  3. var $fieldName; 
  4. var $dateFormat; 
  5. var $ascDesc; 
  6.  
  7. function __construct($fieldName, $ascDesc = 'ASC', $dateFormat = null) { 
  8. $this->ascDesc = strtoupper($ascDesc); 
  9. $this->dateFormat = $dateFormat; 
  10. $this->fieldName = $fieldName; 
  11.  
  12.  
  13. public function sort($a, $b) { 
  14. $aTimeString = isset($a[$this->fieldName]) ? $a[$this->fieldName] : null; 
  15. $bTimeString = isset($b[$this->fieldName]) ? $b[$this->fieldName] : null; 
  16.  
  17. if ($this->dateFormat == null) { 
  18. $aTime = strtotime($aTimeString); 
  19. $bTime = strtotime($bTimeString); 
  20. } else { 
  21. $aTime = $this->parseToTimeStamp($this->dateFormat, $aTimeString); 
  22. $bTime = $this->parseToTimeStamp($this->dateFormat, $bTimeString); 
  23.  
  24. $sortVal = 0; 
  25. // Unset time come before set ones 
  26. if (!$aTime && $bTime) { 
  27. $sortVal = 1; 
  28. } else if ($aTime && !$bTime) { 
  29. $sortVal = -1; 
  30.  
  31. if ($aTime < $bTime) $sortVal = -1; 
  32. if ($aTime > $bTime) $sortVal = 1; 
  33.  
  34. if ($this->ascDesc == 'DESC') { 
  35. $sortVal *= -1; 
  36. return $sortVal; 
  37.  
  38. /** 
  39. * @param $format string date format 
  40. * @param $dateString 
  41. * @return int|null timestamp or null if can't parse 
  42. */ 
  43. public function parseToTimeStamp($format, $dateString) { 
  44. if ($dateString === null) { 
  45. return null; 
  46. // Requires PHP >= 5.3.0 
  47. $t = date_parse_from_format($format, $dateString); 
  48.  
  49. if (isset($t['hour']) && 
  50. isset($t['minute']) && 
  51. isset($t['second']) && 
  52. isset($t['month']) && 
  53. isset($t['day']) && 
  54. isset($t['year']) 
  55. ) { 
  56. return mktime( 
  57. $t['hour'],  
  58. $t['minute'],  
  59. $t['second'],  
  60. $t['month'],  
  61. $t['day'],  
  62. $t['year']); 
  63. } else { 
  64. return null;