Reputation: 13
I need a script to do some date/time conversion. It should take as an input a particular time. It should then generates a series of offsets, in both hour:minute form and number of milliseconds elapsed.
For 03:00, for example, it should give back 04:02:07 (3727000ms*) 05:04:14 (7454000ms), 06:06:21 etc...
How would I go about doing this as a bash script? Ideally it would work on both Mac OS X and Linux (Ubuntu or Debian).
Upvotes: 0
Views: 776
Reputation: 360515
time2ms () {
local time=$1 hour minute second
hour=${time%%:*}
minute=${time#$hour:}
minute=${minute%:*}
second=${time#$hour:$minute}
second=${second/:}
echo "$(( ( (10#${hour} * 60 * 60) + (10#${minute} * 60) + 10#${second} ) * 1000 ))"
}
ms2time () {
local ms=$1 hour minute second
((second = ms / 1000 % 60))
((minute = ms / 1000 / 60 % 60))
((hour = ms / 1000 / 60 / 60))
printf '%02d:%02d:%02d\n' "$hour" "${minute}" "${second}"
}
show_offsets () {
local time=$1 interval=$2 time_ms interval_ms new_time
time_ms=$(time2ms "$time")
interval_ms=$(time2ms "$interval")
new_time=$(ms2time $((time_ms + interval_ms)) )
echo "$new_time (${interval_ms}ms)"
}
Demos:
$ show_offsets 03:00 1:02:07
04:02:07 (3727000ms)
$ show_offsets 03:00 2:04:14
05:04:14 (7454000ms)
$ show_offsets 03:00 3:06:21
06:06:21 (11181000ms)
Upvotes: 2