TimeStamp.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\model\concern;
  12. use DateTime;
  13. /**
  14. * 自动时间戳
  15. */
  16. trait TimeStamp
  17. {
  18. /**
  19. * 是否需要自动写入时间戳 如果设置为字符串 则表示时间字段的类型
  20. * @var bool|string
  21. */
  22. protected $autoWriteTimestamp;
  23. /**
  24. * 创建时间字段 false表示关闭
  25. * @var false|string
  26. */
  27. protected $createTime = 'create_time';
  28. /**
  29. * 更新时间字段 false表示关闭
  30. * @var false|string
  31. */
  32. protected $updateTime = 'update_time';
  33. /**
  34. * 时间字段显示格式
  35. * @var string
  36. */
  37. protected $dateFormat;
  38. /**
  39. * 时间日期字段格式化处理
  40. * @access protected
  41. * @param mixed $format 日期格式
  42. * @param mixed $time 时间日期表达式
  43. * @param bool $timestamp 是否进行时间戳转换
  44. * @return mixed
  45. */
  46. protected function formatDateTime($format, $time = 'now', $timestamp = false)
  47. {
  48. if (empty($time)) {
  49. return;
  50. }
  51. if (false === $format) {
  52. return $time;
  53. } elseif (false !== strpos($format, '\\')) {
  54. return new $format($time);
  55. }
  56. if ($timestamp) {
  57. $dateTime = new DateTime();
  58. $dateTime->setTimestamp($time);
  59. } else {
  60. $dateTime = new DateTime($time);
  61. }
  62. return $dateTime->format($format);
  63. }
  64. /**
  65. * 检查时间字段写入
  66. * @access protected
  67. * @return void
  68. */
  69. protected function checkTimeStampWrite()
  70. {
  71. // 自动写入创建时间和更新时间
  72. if ($this->autoWriteTimestamp) {
  73. if ($this->createTime && !isset($this->data[$this->createTime])) {
  74. $this->data[$this->createTime] = $this->autoWriteTimestamp($this->createTime);
  75. }
  76. if ($this->updateTime && !isset($this->data[$this->updateTime])) {
  77. $this->data[$this->updateTime] = $this->autoWriteTimestamp($this->updateTime);
  78. }
  79. }
  80. }
  81. }