-
Notifications
You must be signed in to change notification settings - Fork 8
/
date-format.sh
executable file
·90 lines (71 loc) · 2.46 KB
/
date-format.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# timestamp, SimpleDateFormat, datetime to string
## datetime now
date +'%d.%m.%Y %H:%M:%S'
date +'%s'
## [T-timestamp](https://github.com/cherkavi/python-utilities/blob/master/datetime/t-time2timestamp.py)
## datetime format nanoseconds
timestamp_nano_seconds=$(date +'%s%N')
# 1678788025759967200
seconds="${timestamp_nano_seconds:0:-9}"
date -d "@$seconds" +"%Y-%m-%d %H:%M:%S"
## datetime miliseconds
echo $(date +'%s%N' | cut -c1-13)
# 1660242155165
## datetime ago
date +'%d.%m.%Y %H:%M:%S' --date="2 hour ago"
date +'%d.%m.%Y' --date="2 day ago"
date +'%d.%m.%Y' --date="2 month ago"
date +'%d.%m.%Y' --date="2 year ago"
## seconds ago
date --date="30 sec ago" +'%s'
## parse datetime parse datetime
date --date="15:21:51 04 Mar 2022" +"%Y.%m.%d %H:%M:%S"
date --date="15:21:51 04 Mar 2022" +%s
## datetime seconds linux time timestamp, seconds to time
date -d @1621508129 '+%Y%m%d %H%M%S'
## with timezone
TZ="America/Los_Angeles" date -d '2021-05-20 10:55:29' +%s
# convert to another timezone
datetime_str_input="2021-03-04 15:21:51"
date --date "TZ=\"UTC\" $datetime_str_input"
# format output, T-time outout
output_format='%Y.%m.%dT%H:%M:%S'
input_datetime_str="2021-03-04 15:21:51"
date +"$output_format" --date "TZ=\"UTC\" $input_datetime_str"
# T-time to seconds
datetime_str="2021.03.04T15:21:51"
input_datetime_str=`echo $datetime_str | tr '.' '-'`
date +"%s" --date "TZ=\"UTC\" $input_datetime_str"
## parse datetime from string
date=$(date +'%Y-%m-%d %H:%M:%S')
read Y M D h m s <<< ${date//[-: ]/ }
### compare date
function diff_in_seconds(){
if [[ $1 == "" ]]; then
echo "first parameter should be time like: 13:30 or 9:15 or 15:5"
return 1
fi
input_value=$1
read h m <<< "${input_value//:/' ' }"
# echo "H=$h, m=$m"
future_in_seconds=$(( "10#"$h * 60 * 60 + "10#"$m * 60 ))
# echo $future_in_seconds
current_date=$(date +'%H %M')
# echo $current_date
read h m <<< $current_date
# echo "H=$h, m=$m"
current_in_seconds=$(( "10#"$h * 60 * 60 + "10#"$m * 60 ))
# echo $current_in_seconds
delay_in_sec=$(( $future_in_seconds - $current_in_seconds ))
if (( $delay_in_sec > 0 )); then
echo $delay_in_sec
else
echo "time should be in future"
fi
}
diff_in_seconds 13:10
# date-compare
date --date="15:21:51 04 Mar 2022" +"%Y.%m.%dT%H:%M:%S"
date +"%Y.%m.%dT%H:%M:%S"
echo "2021.03.04T15:21:51" | xargs -I {} sh -c "if [[ {} < \"$(date +'%Y.%m.%dT%H:%M:%S')\" ]]; then echo 'ok'; fi"
echo $?