5

Is there a way to make a function in vim that takes the difference between two time stamps under highlight?

For example:

1 20:37:00 
2 20:42:30

Supposing you highlight lines 1 and 2 and run the command, say, :TimeDifference, you get the output 5.5 (i.e., 5.5 minutes) which replaces lines 1 and 2.

2 Answers 2

6

You could try the following code:

" line1 is the line number the first timestamp is on.
" line2 is the line number the second timestamp is on.
function! GetTimeDifference(line1,line2)
    " Get line content and split it where ":" matches.
    let l:t1List = split( getline(a:line1), ":" )
    let l:t2List = split( getline(a:line2), ":" )

    " Get the difference in minutes between the timestamps.
    let l:difference = abs(  (l:t1List[0] * 3600 + l:t1List[1] * 60 + l:t1List[2]) - 
                           \ (l:t2List[0] * 3600 + l:t2List[1] * 60 + l:t2List[2])   ) / 60.0

    " Replace the line with the result.
   call setline(a:line1, printf("%.1f" ,l:difference))

    " Delete the other one.
    execute a:line2 . "delete"
endfunction

" Create a user-defined command.
command! -range TimeDifference :call GetTimeDifference(<line1>,<line2>)
0

Use this function.

Select two lines, then :TimeDifference it'll generate the third.**

03:42:53
08:13:18
4 hrs 30 min 25 sec

Inspired from @Jair López code

"" line1 is the line number the first timestamp is on.
" line2 is the line number the second timestamp is on.
function! GetTimeDifference(line1,line2)
    " Get line content and split it where ":" matches.
    let l:t1List = split( getline(a:line1), ":" )
    let l:t2List = split( getline(a:line2), ":" )

    " Get the difference in seconds
    let l:diffSec = abs(  (l:t1List[0] * 3600 + l:t1List[1] * 60 + l:t1List[2]) - 
                           \ (l:t2List[0] * 3600 + l:t2List[1] * 60 + l:t2List[2])   ) 
    let l:sec=trunc(fmod(l:diffSec,60))
    let l:min=trunc(fmod(l:diffSec,3600) / 60) " 60x60
    let l:hrs=trunc(l:diffSec / 3600)

    " Replace the line with the result.
   call append(a:line2, printf("%.0f hrs %.0f min %.0f sec", l:hrs,l:min,l:sec))

    " Delete the other one.
    " execute a:line2 . "delete"
endfunction

" Create a user-defined command.
command! -range TimeDifference :call GetTimeDifference(<line1>,<line2>)

TODO: make it work with a.m. / p.m.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.