This paper proposes a mathematical formulation for energy management in a connected microgrid. The aim is determining the optimal operating strategy for energy storage, to fulfil a time-varying energy demand and operational constraints while achieving a tradeoff between microgrid running costs and energy storage system life. The microgrid is composed by various renewable power production plants, storage devices and controllable loads, and has the ability to increase energy efficiency and reduce costs for energy purchasing from the main grid. The problem is formulated as a mixed-integer linear optimization problem. The optimization is aimed at minimizing the overall cost function of the system while satisfying the customer demand and safety of the electrical network. A case study of an existing microgrid is investigated: the microgrid consists of a photovoltaic and a hydroelectric power plant, a battery storage, an office building and an industrial facility. The optimization problem is solved in an efficient way by using commercial software. Simulation results show the feasibility and the effectiveness of the proposed approach to satisfy the load and reduce total costs.