We prove a spectral flow formula for one-parameter families of Hamiltonian systems under homoclinic boundary conditions, which relates the spectral flow to the relative Maslov index of a pair of curves of Lagrangians induced by the stable and unstable subspaces, respectively. Finally, we deduce sufficient conditions for bifurcation of homoclinic trajectories of one-parameter families of nonautonomous Hamiltonian vector fields.