In this paper, a new and generalized model for the optimal operation of microgrids is presented. The proposed mathematical model considers both operational modes, either grid-connected (GC) and islanded (IS) modes. First, a mixed integer non-linear programming (MINLP) formulation is introduced, modeling the microgrid as an unbalanced ac three-phase electrical distribution system (EDS), comprising distributed generator (DG) units, battery systems (BSs) and wind turbines (WTs). In GC mode, the frequency and the voltage magnitude references are imposed by the main grid at the point of common couple (PCC), while in IS mode, it is assumed that the DG units operate with droop control. Additionally, a set of convexification procedures are introduced in order to approximate the original MINLP model into a new convex formulation that can be solved using commercial solvers. The proposed model has been tested in a 25-bus microgrid for different scenarios, including one where a degradation of the voltage magnitude reference is observed. Results shows that the proposed model is able to properly define the operational mode of the microgrid, based on the technical constraints of the system.