Geeks With Blogs

News My Blog has been MOVED to https://mfreidge.wordpress.com

Michael Freidgeim's OLD Blog My Blog has been MOVED to https://mfreidge.wordpress.com
Previously I've posted a few Helper Classes . This post describes my DateTimeHelper class.

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.VisualBasic.CompilerServices;

using Microsoft.VisualBasic;

using System.Diagnostics;

 

    public static class DateTimeHelper

    {

 

        public static DateTime DateAndTime(DateTime dateValue, DateTime timeValue)

        {

            DateTime time2;

            time2 = new DateTime(dateValue.Year, dateValue.Month, dateValue.Day, timeValue.Hour, timeValue.Minute, timeValue.Second);

            return time2;

        }

 

        public static DateTime DateEndOfDay(DateTime dateValue)

        {

            return DateTimeHelper.DateAndTime(dateValue, DateType.FromString("23:59"));

        }

        public static DateTime DateStartOfDay(DateTime dateValue)

        {

            return DateTimeHelper.DateAndTime(dateValue, DateType.FromString("00:00"));

        }

        //        'Not used

        //        'Public Shared Function TimeAsAccessDate(ByVal Value As Date) As Date

        //        '    Const DateOrigAccess As Date = #1/1/1900#

        //        '    If Value < DateOrigAccess Then

        //        '        Value = DateOrigAccess + " " + Value

        //        '    End If

        //        '    Return (Value)

        //        'End Function

        public static string FormatDateTimeSQL(DateTime Value)

        {

            return DataHelper.Quoted(Strings.Format(Value, "yyyy-MM-dd HH:mm:ss"));

        }

 

        public static string FormatDateTimeSQL(DateTime dateValue, DateTime timeValue)

        {

            return DataHelper.Quoted(Strings.Format(dateValue, "yyyy-MM-dd ") + Strings.Format(timeValue, "HH:mm:ss"));

        }

        public static string TimeConvertSQL(DateTime Value)

        {

            return (" CONVERT(VARCHAR, " + DataHelper.Quoted(Strings.Format(Value, "HH:mm:ss")) + ",108)");

        }

        public static string DateConvertSQL(DateTime Value)

        {

            //        'Using Convert is not good because indexes are not used see http://www.databasejournal.com/features/mssql/print.php/10894_2209321_3.

            return (" CONVERT(DATETIME, " + DateTimeHelper.DateFormatSQL(Value) + " , 102) ");

        }

 

        public static string DateFormatSQL(DateTime Value)

        {

            return DataHelper.Quoted(Strings.Format(Value, "yyyy-MM-dd"));

        }

        public static string SQLBetweenDates(string Field, DateTime FromDate, DateTime ToDate)

        {

            string str = "[" + Field + "] " + SQLBetweenDates(FromDate, ToDate);

            return str;

        }

        public static string SQLBetweenDates(DateTime FromDate, DateTime ToDate)

        {

            string str = "BETWEEN  " + DateConvertSQL(FromDate) + " AND " + FormatDateTimeSQL(DateEndOfDay(ToDate));

            return str;

        }

 

        public static DateTime YYYYMMDDToDate(long day)

        {

            DateTime time3;

            object obj1 = day.ToString();

            time3 = new DateTime(IntegerType.FromString(Strings.Left(StringType.FromObject(obj1), 4)), IntegerType.FromString(Strings.Mid(StringType.FromObject(obj1), 5, 2)), IntegerType.FromString(Strings.Mid(StringType.FromObject(obj1), 7, 2)));

            return time3;

        }

        public static DateTime HHMMSSToTime(long time)

        {

            DateTime time3;

            object obj1 = time.ToString();

            time3 = new DateTime(0x6d9, 1, 1, IntegerType.FromString(Strings.Left(StringType.FromObject(obj1), 2)), IntegerType.FromString(Strings.Mid(StringType.FromObject(obj1), 3, 2)), IntegerType.FromString(Strings.Mid(StringType.FromObject(obj1), 5, 2)));

            return time3;

        }

 

 

        /// <summary>

        /// DateTime string support relative date format e.g. "-1day 20:00" means yesterday at 20:00

        /// </summary>

        /// <param name="sDateTime"></param>

        /// <returns></returns>

        public static DateTime ParseRelativeDateTime(string sDateTime)

        {

            DateTime retDateTime;

            if (DateTime.TryParse(sDateTime, out retDateTime) != true)

            {//support relative date format e.g. "-1day 20:00" means yesterday at 20:00

                string[] sDateTimeParts = sDateTime.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (sDateTimeParts.Length != 2)

                {

                    throw new ArgumentException(String.Format("DateTime format {0} is not recognized ", sDateTime));

                }

                string sRelativeDays = sDateTimeParts[0].Trim();

 

                string sUnitKey = "day";// //todo support month and other

                if (!sRelativeDays.ToLower().EndsWith(sUnitKey))

                {

                    throw new ArgumentException(String.Format("DateTime format {0} is not recognized ", sDateTime));

                }

                sRelativeDays = sRelativeDays.Replace(sUnitKey, "");

                int nDays;

                if (int.TryParse(sRelativeDays, out nDays) != true)

                {

                    throw new ArgumentException(String.Format("Unable to parse relative days {1} from DateTime {0}  ", sDateTime, sRelativeDays));

                }

                TimeSpan tsDays = new TimeSpan(nDays, 0, 0, 0);

                retDateTime = DateTime.Today.Add(tsDays);

                Debug.Assert(retDateTime.Minute == 0);

                Debug.Assert(retDateTime.Hour == 0);

                Debug.Assert(retDateTime.Second == 0);

 

                string sTime = sDateTimeParts[1].Trim();

                DateTime timeOfDay;

                if (DateTime.TryParse(sTime, out timeOfDay) != true)

                {

                    throw new ArgumentException(String.Format("Unable to parse time {1} from DateTime {0} ", sDateTime, sTime));

                }

                retDateTime = new DateTime(retDateTime.Year, retDateTime.Month, retDateTime.Day, timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);

            }

            return retDateTime;

        }

        public static bool IsDayOfWeekInRange(DayOfWeek dayOfWeek, DateTime dateFrom, DateTime dateTo, bool bExcludeEndDate)

        {

            DateTime tempDate = dateFrom;

            //            if(dateFrom> dateTo){ throw new ArgumentException(String.Format("dateFrom {0} must be less or equal than dateTo {1}",dateFrom,  dateTo)};

            DateTime dateEnd = bExcludeEndDate ? dateTo.AddDays(-1) : dateTo;

            while (tempDate <= dateEnd)

            {

                if (tempDate.DayOfWeek == dayOfWeek)

                    return true;

                tempDate = tempDate.AddDays(1);

            }

            return false;

        }

 

        #region  next day of week functions

 

        //from http://forums.asp.net/p/873363/883549.aspx      

        /// <summary>

        /// Gets the next occurence of future day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        /// <param name="dayOfWeek">Next Day of week to find.</param>

        public static DateTime GetNextOccurenceOfDay(DateTime value, DayOfWeek dayOfWeek)

        {

            return GetNextOccurenceOfDay(value, dayOfWeek, false);

        }

        public static DateTime GetNextOccurenceOfDay(DateTime value, DayOfWeek dayOfWeek, bool bIncludeStartDay)

        {

            //TODO add ClosestDay that should start formprovided day

            int daysToAdd = dayOfWeek - value.DayOfWeek;

            int nMinDifference = bIncludeStartDay ? 0 : 1;

            if (daysToAdd < nMinDifference)

            {

                daysToAdd += 7;

            }

            return value.AddDays(daysToAdd);

 

            //DateTime tempDate = value.AddDays(1);

            //while (tempDate.DayOfWeek != dayOfWeek)

            //{

            //    tempDate = tempDate.AddDays(1);

            //}

            //return tempDate;

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime NextMonday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Monday);

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime NextWednesday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Wednesday);

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime NextFriday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Friday);

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime NextSunday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Sunday);

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime NextSaturday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Saturday);

        }

        public static DateTime NextTuesday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Tuesday);

        }

 

        public static DateTime ClosestMonday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Monday, true);

        }

        public static DateTime ClosestTuesday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Tuesday, true);

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime ClosestWednesday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Wednesday, true);

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime ClosestFriday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Friday, true);

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime ClosestSaturday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Saturday, true);

        }

        /// <summary>

        /// Gets the next occurence of speified day.

        /// </summary>

        /// <param name="value">DateTime value to start with.</param>

        public static DateTime ClosestSunday(DateTime value)

        {

            return GetNextOccurenceOfDay(value, DayOfWeek.Sunday, true);

        }

 

 

        #endregion  //next/closest day of week functions

 

 

 

    }

Posted on Wednesday, September 12, 2007 6:37 PM | Back to top


Comments on this post: My DateTimeHelper class

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Michael Freidgeim | Powered by: GeeksWithBlogs.net