import math
from datetime import datetime, timedelta
class
calendarutils
:"""
日期工具類
"""@staticmethod
defdelta_day
(delta=0)
:"""
:param delta: 偏移量
:return: 0今天, 1昨天, 2前天, -1明天 ...
"""return
(datetime.now(
)+ timedelta(days=delta)
).strftime(
'%y-%m-%d'
) @staticmethod
defdelta_week
(delta=0)
:"""
:param delta: 偏移量
:return: 0本週, -1上週, 1下週 ...
"""now = datetime.now(
) week = now.weekday(
) _from =
(now - timedelta(days=week -
7* delta)
).strftime(
'%y-%m-%d'
) _to =
(now + timedelta(days=
6- week +
7* delta)
).strftime(
'%y-%m-%d'
)return _from, _to
@staticmethod
defdelta_month
(delta=0)
:"""
:param delta: 偏移量
:return: 0本月, -1上月, 1下月, 下下個月...
"""def_delta_month
(__year, __month, __delta)
: _month = __month + __delta
if _month <1:
delta_year = math.ceil(
abs(_month)/12
) delta_year = delta_year if delta_year else
1 __year -= delta_year
_month = delta_year *
12+ __month + __delta
elif _month >12:
delta_year = math.floor(_month /12)
__year += delta_year
_month %=
12return __year, _month
now = datetime.now(
) _from = datetime(
*_delta_month(now.year, now.month, delta),1
) _to = datetime(
*_delta_month(_from.year, _from.month,1)
,1)- timedelta(days=1)
return _from.strftime(
'%y-%m-%d'
), _to.strftime(
'%y-%m-%d'
) @staticmethod
defdelta_year
(delta=0)
:"""
:param delta: 偏移量
:return: 0今年, -1去年, 1明年 ...
"""now = datetime.now(
) _from = datetime(now.year + delta,1,
1)_to = datetime(_from.year +1,
1,1)
- timedelta(days=1)
return _from.strftime(
'%y-%m-%d'
), _to.strftime(
'%y-%m-%d'
)if __name__ ==
'__main__'
:print
('當前日期: '
, datetime.now())
print
('*'*40
)print
('今天: '
, calendarutils.delta_day())
print
('昨天: '
, calendarutils.delta_day(-1
))print
('前天: '
, calendarutils.delta_day(-2
))print
('明天: '
, calendarutils.delta_day(1)
)print
('後天: '
, calendarutils.delta_day(2)
)print
('*'*40
)print
('本週: '
, calendarutils.delta_week())
print
('上週: '
, calendarutils.delta_week(-1
))print
('下週: '
, calendarutils.delta_week(1)
)print
('*'*40
)print
('本月: '
, calendarutils.delta_month())
print
('上月: '
, calendarutils.delta_month(-1
))print
('下月: '
, calendarutils.delta_month(1)
)print
('*'*40
)print
('本年: '
, calendarutils.delta_year())
print
('去年: '
, calendarutils.delta_year(-1
))print
('明年: '
, calendarutils.delta_year(1)
)
date 日期工具類
兩個日期相減獲得月份 param startcal param endcal return throws parseexception public static int twodatagetmonth string startcal,string endcal throws parseexcept...
DateUtil日期工具類
public class dateutil category 返回int的值,表示兩個指定日期間的時間間隔數目 public static int datediff string interval,date date1,date date2 throws exception interval 季 i...
日期時間工具類
取得當前日期所在周的第一天 param date return public static date getfirstdayofweek date date 取得當前日期所在周的最後一天 param date return public static date getlastdayofweek da...