8

My system displayed the time like this 10:42 when i input the command date +%R. I need to take in total minutes of the time. That means like this 642 minutes. Is there any command or shell script for displaying total time in minutes?

0

5 Answers 5

11

To only get the total minutes of the day, I would use the following command:

$ date "+%H*60+%M" | bc

Example:

$ date +%R
09:30
$ date "+%H*60+%M" | bc
570

The trick is to format the date output to allow bc to interpret and calculate the formula.

4
  • 2
    If you use echo $(date +"%H*60+%M") | bc, it works also in zsh ;)
    – A.B.
    Jul 10, 2015 at 12:25
  • @A.B. One day I'll switch over to zsh Jul 10, 2015 at 12:28
  • 1
    date "+%H*60+%M" | bc works just as well too. Probably in just about any shell. Jul 10, 2015 at 17:24
  • @DigitalTrauma: Simple, thanks. I've updated my answer accordingly. Jul 10, 2015 at 18:26
5

just bash:

IFS=: read hour min < <(date +%R)
echo $(( 60 * 10#$hour + 10#$min ))

Forcing both variables to be treated as base-10, to avoid the shell throwing errors for invalid octal numbers 08 and 09

2
  • Yes, echo $(( $(date "+%k * 60 + 10#%M") )) is what I meant to say Jul 10, 2015 at 19:05
  • 1
    Yeah nothing wrong with that. Maybe my answer is a little more ... instructional Jul 10, 2015 at 19:08
3
date +%R | awk -F ":" '{print ($1 * 60) + $2}'

Or

 echo $((($(date +%l) * 60 ) + $(date +%M)))

date +%l will get the hours , multiply with 60 and add minutes date +%M

2

Using date and bash:

eval "$(date +'today=%F now=%s')"; midnight=$(date -d "$today 0" +%s);echo "$(((now - midnight) / 60))"

Example

$ date
Fr 10. Jul 08:45:05 CEST 2015

$ eval "$(date +'today=%F now=%s')"; midnight=$(date -d "$today 0" +%s);echo "$(((now - midnight) / 60))"
525

Using date and an the z-shell (zsh):

IFS=:; set -- $(date +%T); echo "$((($1 * 3600 + $2 * 60 + $3) / 60))"

Example

% date
Fr 10. Jul 08:40:53 CEST 2015

% IFS=:; set -- $(date +%T); echo "$((($1 * 3600 + $2 * 60 + $3) / 60))"
520
3
  • 1
    @DineshDhananjayan Were you satisfied with my answer? Then give me an upvote (∧). If I could solve your problem, then it would be nice if you'd mark my answer (✓). askubuntu.com/help/someone-answers ;)
    – A.B.
    Jul 10, 2015 at 9:37
  • 1
    I don't think your zsh answer is correct: IFS=: set -- $(date +%T); echo $1 returns 08:16:52 -- you'll need IFS=:; set ... Jul 10, 2015 at 12:20
  • @glennjackman Ups and thank you, corrected. :\
    – A.B.
    Jul 10, 2015 at 12:24
1

You don't need to use IFS, you can do it this way:

date=$(date +'%l:%M')
read H M <<< ${date//[-: ]/ }
echo  "Total minutes: $(($H * 60 + $M))"

output is:

Total minutes: 593
1
  • I have corrected your answer. The error message was bash: 9 17*60+: syntax error in expression (error token is "17*60+")
    – A.B.
    Jul 10, 2015 at 7:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .