Date/Time Utility tool

using System;
using System.Collections;
using Microsoft.Win32;
namespace EQTG.General.BasicTypes
{
    /// <summary>
    /// Simple useful time based functions not supplied by the .NET framework or EQTG specific in usefulness
    /// </summary>
    public sealed class TimeUtils
    {
        private TimeUtils()
        {
        }

        /// <summary>
        /// Class diagnostics instance
        /// </summary>
        //private static ClassDiagnostics OurDiagnostics = new ClassDiagnostics();

        /// <summary>
        /// Constant defining the number of seconds in an hour
        /// </summary>
        public const System.Int32 SecondsPerHour = 60 * 60;

        /// <summary>
        /// Constant defining the number of seconds in a day
        /// </summary>
        public const System.Int32 SecondsPerDay = SecondsPerHour * 24;

        /// <summary>
        /// Constant defining the number of minutes in a day
        /// </summary>
        public const System.Int32 MinutesPerDay = 24 * 60;

        /// <summary>
        /// DateTime objects have a notional granuality of Ticks. 1 Tick = 100 nanoseconds. TicksPerSecond Ticks = 1 second
        /// </summary>
        public const long TicksPerSecond = 10000000L;

        /// <summary>
        /// Turn a datetime into a time int that is used for instance on the TIC
        /// </summary>
        /// <param name="dt">System.DateTime to be turned into integer</param>
        /// <returns>Int representing the time</returns>
        public static int TimeAsInteger( System.DateTime dt )
        {
            int timeAsInteger        =    dt.Hour * 10000000;
            timeAsInteger        +=    dt.Minute * 100000;
            timeAsInteger        +=    dt.Second * 1000;
            timeAsInteger        +=    dt.Millisecond % 1000;
            return timeAsInteger;
        }

        /// <summary>
        /// Turn a time int (that is used for instance on the TIC) into a DateTime during the current day
        /// </summary>
        /// <param name="timeAsInteger"></param>
        /// <returns></returns>
        public static DateTime TodayTimeFromInteger( int timeAsInteger )
        {
            return TimeFromIntegerAndBaseDate( timeAsInteger, DateTime.Now);
        }

        /// <summary>
        /// Turn a time int (that is used for instance on the TIC) into a DateTime on 1 Jan 1900
        /// </summary>
        /// <param name="timeAsInteger"></param>
        /// <returns></returns>
        public static DateTime YearDotTimeFromInteger( int timeAsInteger )
        {
            return TimeFromIntegerAndBaseDate( timeAsInteger, DateTime.MinValue);
        }

        /// <summary>
        /// Turn a time int (that is used for instance on the TIC) into a DateTime in the same day as baseDate
        /// </summary>
        /// <param name="timeAsInteger"></param>
        /// <param name="baseDate"></param>
        /// <returns></returns>
        public static DateTime TimeFromIntegerAndBaseDate( int timeAsInteger, DateTime baseDate )
        {
            int hour, minute, second, millisecond;
            timeAsInteger -= (hour = timeAsInteger / 10000000) * 10000000;
            timeAsInteger -= (minute = timeAsInteger / 100000) * 100000;
            timeAsInteger -= (second = timeAsInteger / 1000) * 1000;
            millisecond = timeAsInteger;
            DateTime dateTime = new DateTime(baseDate.Year, baseDate.Month, baseDate.Day, hour, minute, second, millisecond);
            return dateTime;
        }

        /// <summary>
        /// Turn a system date time into a rover8 date (useful for database queries etc)
        /// </summary>
        /// <param name="dt">System.DateTime to be converted</param>
        /// <returns>Int of form 20020330</returns>
        public static int  Rover8FromDateTime( System.DateTime dt )
        {
            return dt.Year*10000 + dt.Month * 100 + dt.Day;
        }

        /// <summary>
        /// Datetime year month and date from rover8 string
        /// </summary>
        /// <param name="s">Rover8 String</param>
        /// <param name="dt">DateTime to set</param>
        /// <returns>Whether conversion succeeded</returns>
        public static bool DateTimeFromRover8String( out DateTime dt, string s )
        {
            try
            {
                int rover8Number = int.Parse( s );
                int year        = ( rover8Number / 10000 );
                int month        = ( rover8Number / 100 ) % 100;
                int day            = rover8Number % 100;

                dt = new DateTime( year, month, day, 0,0,0 );
                return true;
            }
            catch ( Exception e)
            {
                dt = DateTime.MinValue;
                return false;
            }
        }

        /// <summary>
        /// Converts a datetime into a format suitable for embedding into a sybase SQL statement
        /// A datetime value of DateTime.MinValue will reuslt in "NULL" being returned
        /// </summary>
        /// <param name="inString">string</param>
        public static string ToDatabase(DateTime dateTime)
        {    
            if (dateTime == DateTime.MinValue)    // Interpretted as NULL
                return "NULL";
            else
                return String.Format("'{0:MMM dd yyyy HH:mm}'", dateTime);
            //if
        }
        
        /// <summary>
        /// Bump specified DateTime past a weekend.
        /// No timezone adjustments made - straight 24-hour chunks added.
        /// Doesn't do any timezone conversions
        /// </summary>
        /// <param name="dt">Date Time to bump</param>
        /// <returns>Bumped DateTime</returns>
        public static DateTime BumpPastWeekend( DateTime dt )
        {
            switch ( dt.DayOfWeek )
            {
                case DayOfWeek.Saturday:
                    MoveDateTimeForwardToNextDay(ref dt);
                    MoveDateTimeForwardToNextDay(ref dt);
                    break;
                case DayOfWeek.Sunday:
                    MoveDateTimeForwardToNextDay(ref dt);
                    break;
            }
            return dt;

        }

        /// <summary>
        /// Moves the passed DateTime back until we hit the previous day.
        /// Inputs and outputs are both local time. We have to be careful because in DST adjustment days,
        /// the day can be longer or shorter than 24 hours.  We assume that the adjustment will not be more than 2 hours, and
        /// that days are longer than 2 hours :)
        /// </summary>
        /// <param name="dt">time to move</param>
        public static void MoveDateTimeBackToPrevDay( ref DateTime dt )
        {
            int curDay = dt.Day;
            dt.AddHours(-22);
            while (dt.Day == curDay)
                dt = dt.AddHours(-1);
        }

        /// <summary>
        /// Moves the passed DateTime forward until we hit the next day.
        /// Inputs and outputs are both local time. We have to be careful because in DST adjustment days,
        /// the day can be longer or shorter than 24 hours.  We assume that the adjustment will not be more than 2 hours, and
        /// that days are longer than 2 hours :)
        /// </summary>
        /// <param name="dt">time to move</param>
        public static void MoveDateTimeForwardToNextDay( ref DateTime dt )
        {
            int curDay = dt.Day;
            dt.AddHours(22);
            while (dt.Day == curDay)
                dt = dt.AddHours(1);
        }

        /// <summary>
        /// Gets the UTC <see cref="DateTime"/> (moves specified DateTime back) at which the local time in
        /// the specified time zone was the time specified.
        /// </summary>
        /// <remarks>
        /// Inputs and outputs are UTC.  Converts to local time, gets the previous
        /// occurrence of specified local hour and minute, returns as UTC
        /// </remarks>
        /// <param name="utcStart">Test time</param>
        /// <param name="timezone">Timezone of test time</param>
        /// <param name="hour">Hour of prev occurrence</param>
        /// <param name="minute">Minute of prev occurrence</param>
        /// <returns>Previous Weekday UTC DateTime to test date</returns>

        /// <summary>
        /// Gets the UTC <see cref="DateTime"/> (moves specified DateTime back) at which the local
        /// time in the specified time zone will next be the time specified.
        /// </summary>
        /// <remarks>
        /// Inputs and outputs are UTC.  Converts to local time, gets the next occurrence of specified
        /// local hour and minute, returns as UTC
        /// </remarks>
        /// <param name="utcStart">Test time</param>
        /// <param name="timezone">Timezone of test time</param>
        /// <param name="hour">Hour of prev occurrence</param>
        /// <param name="minute">Minute of prev occurrence</param>
        /// <returns>Previous Weekday UTC DateTime to test date</returns>
        public static string XMLStringToDateString(string xmlString)
        {
            string result = "";
            try
            {
                DateTime date = DateTime.ParseExact(xmlString, "yyyy-MM-dd", new System.Globalization.DateTimeFormatInfo());
                result = String.Format("{0:dd MMM yyyy}", date);
            }
            catch (FormatException)
            {
            }

            return result;
        }

        public static DateTime Max(DateTime a, DateTime b)
        {
            return a > b ? a : b;
        }

        public static DateTime Min(DateTime a, DateTime b)
        {
            return a > b ? b : a;
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章