4

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.

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>)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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