A measurement of mixing and CP violation in neutral charm mesons is performed using data reconstructed in proton-proton collisions collected by the LHCb experiment from 2016 to 2018, corresponding to an integrated luminosity of 5.4 fb−1. A total of 30.6 million D0→K0Sπ+π− decays are analyzed using a method optimized for the measurement of the mass difference between neutral charm-meson eigenstates. Allowing for CP violation in mixing and in the interference between mixing and decay, the mass and decay-width differences are measured to be xCP=[3.97±0.46(stat)±0.29(syst)]×10−3 and yCP=[4.59±1.20(stat)±0.85(syst)]×10−3, respectively. The CP-violating parameters are measured as Δx=[−0.27±0.18(stat)±0.01(syst)]×10−3 and Δy=[0.20±0.36(stat)±0.13(syst)]×10−3. This is the first observation of a nonzero mass difference in the D0 meson system, with a significance exceeding seven standard deviations. The data are consistent with CP symmetry and improve existing constraints on the associated parameters.