Some shells are able to do the work without calling an external date
command:
ksh
a=$(printf '%(%s)T\n'); printf '%(%Y.%m.%d %H:%M)T\n' "#$((a-a%(15*60)))"
bash a=$(printf '%(%s)T\n'); printf '%(%Y.%m.%d %H:%M)T\n' "$((a-a%(15*60)))"
zsh zmodload zsh/datetime; a=$EPOCHSECONDS; strftime '%Y-%m-%d %H:%M' $((a-a%(15*60)))
The three above provide local (not UTC) time. Use a leading TZ=UTC0 if needed.
The ksh and bash syntax is almost identical (except for the required #
in ksh). The zsh require to load a module (included with the zsh distribution).
It is also possible to do it with (GNU) awk:
gawk awk 'BEGIN{t=systime();print strftime("%Y.%m.%d %H:%M",t-t%(15*60),1)}'
This provide an UTC result (change the last 1
to 0
) if local is needed.
But loading an external awk or an external zsh module might be as slow as calling date itself:
gnu-date a=$(date +%s); date -ud "@$((a-a%(15*60)))" +'%Y.%m.%d %H:%M'
A small executable like busybox
could provide similar results:
busybox-date a=$(busybox date +%s);busybox date -ud "@$((a-a%(15*60)))" +'%Y.%m.%d %H:%M'
Note that the leading busybox word may be omitted if busybox is linked to those names in a directory of the PATH.
Both date
and busybox date
above will print UTC times. Remove the -u
option for local times.
If your OS has a more limited version of date (and that is what you must use) then try:
a=$(date +%s); a=$(( a-a%(15*60) ))
date -d"1970-01-01 $a seconds UTC" +'%Y.%m.%d %H:%M'
Or, if in FreeBSD, try:
a=$(date +%s); a=$(( a-a%(15*60) ))
date -r "$a" +'%Y.%m.%d %H:%M'