We show how statistical thermodynamics can be formulated in situations of metaequilibrium or metastability (as in the cases of supercooled liquids or of glasses respectively). By analogy with phenomenological thermodynamics, the primary quantities considered are the heat Q absorbed and the work W performed by the system of interest. These are defined through the energy exchanges which occur when the system is put in contact with a thermostat and with a barostat, the whole system being dealt with as a global Hamiltonian dynamical system. The coefficients of the fundamental form turn out to have such expressions that the closure of the form is manifest: this gives the first principle. A further step is performed by making use of time reversibility. This provides new expressions for the coefficients, such that the second principle in the form of Clausius is also manifest. Such coefficients are expressed in terms of time-autocorrelations of suitable dynamical variables, in a way analogous to that of fluctuation dissipation theory for equilibrium states. All these results are independent of the ergodicity properties of the global dynamical system.