Round Date Time - CSharp System

CSharp examples for System:DateTime Calculate

Description

Round Date Time

Demo Code

/*//ww  w  .ja  v  a  2  s . c  om
    Copyright (C) 2007-2014 Team MediaPortal
    http://www.team-mediaportal.com

    This file is part of MediaPortal 2

    MediaPortal 2 is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MediaPortal 2 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MediaPortal 2. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Globalization;
using System;

public class Main{
        public static DateTime RoundDateTime(this DateTime dt, int minutes, RoundingDirection direction)
    {
      TimeSpan t;
      switch (direction)
      {
        case RoundingDirection.Up:
          t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes, 0));
          break;
        case RoundingDirection.Down:
          t = (dt.Subtract(DateTime.MinValue));
          break;
        default:
          t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes / 2, 0));
          break;
      }
      return DateTime.MinValue.Add(new TimeSpan(0, (((int)t.TotalMinutes) / minutes) * minutes, 0));
    }
}

Related Tutorials