Scattering of femtosecond laser pulses on resonant transmission and reflection gratings made of dispersive (Drude metals) and dielectric materials is studied by a time-domain numerical algorithm for Maxwell's theory of linear passive (dispersive and absorbing) media. The algorithm is based on the Hamiltonian formalism in the framework of which Maxwell's equations for passive media are shown to be equivalent to the first-order equation, ∂Ψ/∂t = HΨ, where H is a linear differential operator (Hamiltonian) acting on a multi-dimensional vector Ψ built of the electromagnetic inductions and auxiliary matter fields describing the medium response. The initial value problem is then solved by means of a modified time leapfrog method in combination with the Fourier pseudospectral method applied on a non-uniform grid that is constructed by a change of variables and designed to enhance the sampling efficiency near medium interfaces. The algorithm is shown to be highly accurate at relatively low computational costs. An excellent agreement with previous theoretical and experimental studies of the gratings is demonstrated by numerical simulations using our algorithm. In addition, our algorithm allows one to see real time dynamics of long leaving resonant excitations of electromagnetic fields in the gratings in the entire frequency range of the initial wide band wave packet as well as formation of the reflected and transmitted wave fronts.