Guest User

Untitled

a guest
Dec 15th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. SELECT DATE_SUB('2004-12-31', INTERVAL 3 MONTH)
  2.  
  3. $maxDate = '2004-12-31';
  4. $timestamp = ;
  5. echo date('Y-m-d', strtotime($maxDate . ' - 3 month'));
  6.  
  7. $Date = new DateTime('2004-12-31');
  8. $Date->sub(DateInterval::createFromDateString('3 months'));
  9. echo $Date->format('Y-m-d');
  10.  
  11. echo findDate('2004-12-31', -3); // 2004-09-29
  12.  
  13. function findDate($start_date, $months) {
  14. $start_date_object = new DateTime($start_date);
  15. $date_interval = findInterval($months, $start_date_object);
  16. $end_date_object = $start_date_object->add($date_interval);
  17. $end_date_object->sub(new DateInterval('P1D'));
  18. return $end_date_object->format('Y-m-d');
  19. }
  20.  
  21. function findInterval($n_months, DateTime $start_date_object) {
  22. $date_of_last_day_next_month = new DateTime($start_date_object->format('Y-m-d'));
  23. $date_of_last_day_next_month->modify('last day of +'.$n_months.' month');
  24. if($start_date_object->format('d') > $date_of_last_day_next_month->format('d')) {
  25. return $start_date_object->diff($date_of_last_day_next_month);
  26. } else {
  27. return new DateInterval('P'.$n_months.'M');
  28. }
  29. }
  30.  
  31. $Date = new DateTime('2004-12-31');
  32. $shift = -3;
  33.  
  34. // сохраним день
  35. $day = $Date->format('d');
  36. // первый день целевого месяца
  37. $Date->modify('first day of this month')->modify(($shift > 0 ? '+':'') . $shift . ' months');
  38. // если наш день больше числа дней в месяце, возьмем последний
  39. $day = $day > $Date->format('t') ? $Date->format('t') : $day;
  40. // готово
  41. echo $Date->modify('+' . $day-1 . ' days')->format('c');
  42.  
  43. function subMonths(Datetime $dateTime, int $months)
  44. {
  45. if ($invert = $months < 0) {
  46. $months *= -1;
  47. }
  48.  
  49. for ($i=0; $i<$months; $i++) {
  50. $daysOfMonth = cal_days_in_month(CAL_GREGORIAN, $dateTime->format('m'), $dateTime->format('Y'));
  51. $dateTime->modify(($invert ? '-' : '+') . $daysOfMonth . ' day');
  52. }
  53. return $dateTime;
  54. }
  55.  
  56. $dateTime = new DateTime('2004-12-31');
  57. echo subMonths($dateTime, -3)->format('Y-m-d'); // 2004-09-30
Add Comment
Please, Sign In to add comment