-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datetime.sh
48 lines (44 loc) · 1.86 KB
/
datetime.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
unixtime() {
set -- "$1" "${2:--utc}" && [ "$2" = -local ] && set -- "$1"
datetime2unixtime "$1" "$(date ${2+-u} +'%Y-%m-%dT%H:%M:%S')"
}
datetime2unixtime() {
set -- "$1" "${2%%-*}" "${2%%T*}" "${2##*T}"
set -- "$1" "${2#"${2%%[!0]*}"}" "${3#*-}" "${4%%:*}" "${4#*:}"
set -- "$1" "$2" "${3%%-*}" "${3#*-}" "$4" "${5%%:*}" "${5#*:}"
set -- "$1" "${2:-0}" "${3#0}" "${4#0}" "${5#0}" "${6#0}" "${7#0}"
[ "$3" -lt 3 ] && set -- "$1" $(($2-1)) $(($3+12)) "$4" "$5" "$6" "$7"
set -- "$1" $((365*$2+$2/4-$2/100+$2/400)) "$3" "$4" "$5" "$6" "$7"
set -- "$1" "$2" $(((306*($3+1)/10)-428)) "$4" "$5" "$6" "$7"
eval "$1=$((($2+$3+$4-719163)*86400+$5*3600+$6*60+$7))"
}
unixtime2datetime() {
set -- "$1" $(($2%86400)) $(($2/86400+719468)) 146097 36524 1461
set -- "$@" $(($3-(($3+2+3*$3/$4)/$6)+($3-$3/$4)/$5-(($3+1)/$4)))
set -- "$1" "$2" "$3" $(($7/365))
set -- "$1" "$2" "$4" $(($3-(365*$4+$4/4-$4/100+$4/400)))
set -- "$1" "$2" "$3" "$4" $((($4-($4+20)/50)/30))
set -- "$1" "$2" "$4" "$5" $((12*$3+$5+2))
set -- "$@" $(($5/12)) $(($5%12+1)) $(($3-(30*$4+3*($4+4)/5-2)+1))
set -- "$1" "$6" "$7" "$8" $(($2/3600)) $(($2%3600/60)) $(($2%3600%60))
set -- "$1" "$2" $(($3+100)) $(($4+100)) $(($5+100)) $(($6+100)) $(($7+100))
eval "$1=$2-${3#1}-${4#1}T${5#1}:${6#1}:${7#1}"
}
last_day_of_month() {
set -- "$1" "${2%%-*}" "${2%%T*}" "${2##*T}"
set -- "$1" "${2#"${2%%[!0]*}"}" "${3#*-}"
set -- "$1" "${2:-0}" "${3%-*}"
case ${3#0} in
1 | 3 | 5 | 7 | 8 | 10 | 12) set -- "$1" "$2" "$3" 31 ;;
4 | 6 | 9 | 11) set -- "$1" "$2" "$3" 30 ;;
2) set -- "$1" "$2" "$3" $(( 28+($2%4==0 && ($2%100!=0 || $2%400==0)) ))
esac
eval "$1=$2-$3-$4"
}
weekday() {
set -- "$1" "$2" "${2%%T*}"
datetime2unixtime "$1" "$2T00:00:00"
eval "set -- \"\$1\" \"\$$1\""
set -- "$1" $(( ($2 / 86400 + 3) % 7 + 1 )) mon tue wed thu fri sat sun
eval "$1=\$$(($2 + 2)):$2"
}