During the last decade, microgrids are attracting a significant attention due to their numerous advantages. Amongst them, the most important one is their ability to operate either in grid-connected or in islanded (autonomous) mode. However, the transition between the two modes can be challenging in terms of maintaining the stability and integrity of the microgrid. In this paper, an optimization-based islanding methodology is developed to ensure a timely and smooth transition from the grid-connected to the islanded mode. This is achieved through shedding loads, by defining the generation level of the photovoltaics (energy spill) and by regulating the charging/discharging rate of batteries. A resynchronization method is also presented along with the requirements that need to be satisfied for the smooth reconnection of the microgrid back to the main grid. The effectiveness of the proposed approach is demonstrated through simulation results for the events of surplus energy production, and excess energy demand of the microgrid.