Esempio n. 1
0
        /// <summary>
        /// Gets the time format to use from the supplied globalization service.
        /// </summary>
        /// <param name="gs">Globalization service to get format from.</param>
        /// <param name="displaySeconds">Whether to display seconds.</param>
        /// <param name="display12Hour">Whether to use 12 hour or 24 hour clock.</param>
        /// <param name="displayAMPM">Whether to display am / pm indicator.</param>
        /// <returns>Time format.</returns>
        public static string GetTimeFormat(GlobalizationService gs, bool displaySeconds, bool display12Hour, bool displayAMPM)
        {
            string format;

            if (displaySeconds)
            {
                if (display12Hour)
                {
                    format = displayAMPM ? gs.ShortTimePatternWithSeconds12HourAMPM :
                             gs.ShortTimePatternWithSeconds12Hour;
                }
                else
                {
                    format = displayAMPM ? gs.ShortTimePatternWithSecondsAMPM :
                             gs.ShortTimePatternWithSeconds;
                }
            }
            else
            {
                if (display12Hour)
                {
                    format = displayAMPM ? gs.ShortTimePattern12HourAMPM :
                             gs.ShortTimePattern12Hour;
                }
                else
                {
                    format = displayAMPM ? gs.ShortTimePatternAMPM :
                             gs.ShortTimePattern;
                }
            }

            return(format);
        }
Esempio n. 2
0
        public string ToString(bool approximate, CultureInfo cultureInfo, bool displaySeconds, bool display12Hour, bool displayAMPM)
        {
            if (approximate && this.TimeType != TimeType.Approximate)
            {
                // This is invalid. You cannot make use of the indicateWhenApproximate flag when the
                // TimeType is not Approximate
                throw new ArgumentOutOfRangeException("approximate", Resources.CuiTimeResources.ShowApproxIndicatorInvalidForTimeType);
            }

            string formattedTime;

            switch (this.TimeType)
            {
            case TimeType.Exact:
            case TimeType.Approximate:
                GlobalizationService gs = new GlobalizationService();

                // we never return a string such as "14:04 (pm)"
                bool reallyDisplayAMPM = displayAMPM && (display12Hour || this.TimeValue.TimeOfDay.Hours < 12);

                string format = GetTimeFormat(gs, displaySeconds, display12Hour, reallyDisplayAMPM);

                formattedTime = this.timeValue.ToString(format, cultureInfo);

                if (reallyDisplayAMPM)
                {
                    // make am / pm lowercase
                    formattedTime = formattedTime.ToLower(cultureInfo);
                }

                if (approximate)
                {
                    // prepend "Approx" indicator
                    formattedTime = string.Format(
                        cultureInfo,
                        Resources.CuiTimeResources.ApproximateTimeFormat,
                        Resources.CuiTimeResources.Approximate,
                        formattedTime);
                }

                break;

            case TimeType.NullIndex:
                formattedTime = string.Format(cultureInfo, "Null:{0}", this.NullIndex);
                break;

            case TimeType.Null:
                formattedTime = string.Empty;
                break;

            default:
                throw new InvalidOperationException();
            }

            return(formattedTime);
        }
Esempio n. 3
0
        /// <summary>
        /// Returns a string representing the date.
        /// </summary>
        /// <param name="includeDayOfWeek">Includes the day of the week in the string. </param>
        /// <param name="approximate">When the <see cref="P:Microsoft.Cui.Controls.Common.DateAndTime.CuiDate.DateType">DateType</see>
        /// is DateType.Approximate, shows the Approx text indicator.</param>
        /// <param name="showRelativeDayText">If the date is Today, Tomorrow or Yesterday, returns a string rather than the date. </param>
        /// <param name="cultureInfo">The culture that should be used to parse the string. </param>
        /// <returns>The date as a string. </returns>
        public string ToString(bool includeDayOfWeek, bool approximate, bool showRelativeDayText, CultureInfo cultureInfo)
        {
            if (cultureInfo == null)
            {
                throw new ArgumentNullException("cultureInfo");
            }

            if (this.DateType != DateType.Approximate && approximate == true)
            {
                // This is invalid. You cannot make use of the indicateWhenApproximate flag when the
                // Date is not Approximate
                throw new ArgumentOutOfRangeException("approximate", Resources.CuiDateResources.ShowApproxIndicatorInvalidForDateType);
            }

            string formattedDate = null;

            switch (this.dateType)
            {
            case DateType.Exact:
            case DateType.Approximate:

                if (showRelativeDayText)
                {
                    DateTime date = this.DateValue.Date;
                    if (date == System.DateTime.Today)
                    {
                        formattedDate = Resources.CuiDateResources.Today;
                    }
                    else if (date == System.DateTime.Today.AddDays(-1))
                    {
                        formattedDate = Resources.CuiDateResources.Yesterday;
                    }
                    else if (date == System.DateTime.Today.AddDays(1))
                    {
                        formattedDate = Resources.CuiDateResources.Tomorrow;
                    }
                }

                if (formattedDate == null)
                {
                    GlobalizationService gs = new GlobalizationService();
                    formattedDate = this.DateValue.ToString(includeDayOfWeek ? gs.ShortDatePatternWithDayOfWeek : gs.ShortDatePattern, cultureInfo);
                }

                if (this.DateType == DateType.Approximate && approximate)
                {
                    formattedDate = string.Format(
                        cultureInfo,
                        Resources.CuiDateResources.ApproximateDateFormat,
                        Resources.CuiDateResources.Approximate,
                        formattedDate);
                }

                break;

            case DateType.Year:
                formattedDate = this.Year.ToString("0000", cultureInfo);
                break;

            case DateType.YearMonth:
                formattedDate = string.Format(
                    cultureInfo,
                    "{0}-{1}",
                    cultureInfo.DateTimeFormat.MonthNames[this.Month - 1],
                    this.Year.ToString("0000", cultureInfo));
                break;

            case DateType.NullIndex:
                formattedDate = string.Format(cultureInfo, "Null:{0}", this.NullIndex);
                break;

            case DateType.Null:
                formattedDate = string.Empty;
                break;

            default:
                throw new InvalidOperationException();
            }

            return(formattedDate);
        }
Esempio n. 4
0
        /// <summary>
        /// Parses a string that represents a time.
        /// </summary>
        /// <param name="time">A string containing the value to be parsed. </param>
        /// <param name="result">A container for a successfully-parsed time. </param>
        /// <param name="cultureInfo">The culture that should be used to parse the string. If a string is culture-agnostic,
        /// this should be CultureInfo.InvariantCulture. Defaults to CurrentCulture.</param>
        /// <returns>True if time string was successfully parsed; otherwise, false. </returns>
        /// <remarks>If the string be parsed, the result parameter is set to a CuiTime object corresponding to the parsed timeString.
        /// If the time string cannot be parsed, the result parameter is set to DateTime.MinValue. </remarks>
        public static bool TryParseExact(string time, out CuiTime result, IFormatProvider cultureInfo)
        {
            result = null;

            // check for true null
            if (string.IsNullOrEmpty(time))
            {
                result          = new CuiTime();
                result.TimeType = TimeType.Null;
                return(true);
            }

            bool approxIndicatorPresent = false;

            // first check to see if approx indicator is present
            if (time.IndexOf(Resources.CuiTimeResources.Approximate, StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                time = time.Replace(Resources.CuiTimeResources.Approximate, string.Empty).Trim();
                approxIndicatorPresent = true;
            }

            DateTime parsedDateTime;

            // try standard datetime parse with our custom formats
            GlobalizationService gs = new GlobalizationService();

            string[] formats = new string[]
            {
                gs.ShortTimePattern,
                gs.ShortTimePatternWithSeconds,
                gs.ShortTimePatternAMPM,
                gs.ShortTimePatternWithSecondsAMPM,
                gs.ShortTimePattern12Hour,
                gs.ShortTimePatternWithSeconds12Hour,
                gs.ShortTimePattern12HourAMPM,
                gs.ShortTimePatternWithSeconds12HourAMPM
            };

            if (DateTime.TryParseExact(time, formats, cultureInfo, DateTimeStyles.None, out parsedDateTime))
            {
                result = new CuiTime(parsedDateTime, approxIndicatorPresent);
                return(true);
            }

            if (!approxIndicatorPresent)
            {
                // Check if 'time' is a Null time
                Regex nullTimeRegEx = new Regex(@"^Null:(?<Index>-?\d+)$", RegexOptions.IgnoreCase);

                Match match = nullTimeRegEx.Match(time);

                if (match.Success == true)
                {
                    // Pull the numeric Index text and see if it is in range
                    int nullIndex;

                    if (int.TryParse(match.Groups[1].Captures[0].Value, out nullIndex) == true)
                    {
                        if (nullIndex >= MinimumNullIndex && nullIndex <= MaximumNullIndex)
                        {
                            result = new CuiTime();

                            result.NullIndex = nullIndex;
                            result.TimeType  = TimeType.NullIndex;
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Esempio n. 5
0
        /// <summary>
        /// Parses a string that represents a date.
        /// </summary>
        /// <param name="date">A string containing the value to be converted.   </param>
        /// <param name="result">A container for a successfully-parsed date.  </param>
        /// <param name="cultureInfo">The culture that should be used to parse the string.</param>
        /// <returns>True if the date string was successfully parsed; otherwise, false.  </returns>
        /// <remarks>
        ///  If the string can be parsed,
        /// the result parameter is set to an CuiDate object corresponding to
        /// the parsed dateString. If the string cannot be parsed, the result parameter is set to DateTime.MinValue.
        /// </remarks>
        public static bool TryParseExact(string date, out CuiDate result, CultureInfo cultureInfo)
        {
            // check for true null
            if (string.IsNullOrEmpty(date))
            {
                result          = new CuiDate();
                result.DateType = DateType.Null;
                return(true);
            }

            // first check for numeric year month as this can be confused as a date
            Regex numericYearMonthRegEx        = new Regex("^(?<Month>0?[1-9]|10|11|12)[-\\s/](?<Year>\\d{4}|\\d{2})$");
            Match numericYearMonthRegExResults = numericYearMonthRegEx.Match(date);

            if (numericYearMonthRegExResults.Success)
            {
                result          = new CuiDate();
                result.DateType = DateType.YearMonth;
                result.Month    = int.Parse(numericYearMonthRegExResults.Groups["Month"].Value, cultureInfo);
                result.Year     = CuiDate.ParseYear(numericYearMonthRegExResults.Groups["Year"].Value, cultureInfo);

                return(true);
            }

            // check to see if approx indicator is present
            bool approxIndicatorPresent = (date.IndexOf(Resources.CuiDateResources.Approximate, StringComparison.CurrentCultureIgnoreCase) >= 0);

            if (approxIndicatorPresent)
            {
                date = date.Replace(Resources.CuiDateResources.Approximate, string.Empty).Trim();
            }

            // try datetime parse with our standard formats
            GlobalizationService gs = new GlobalizationService();

            string[] standardFormats = new string[]
            {
                gs.ShortDatePattern,
                gs.ShortDatePatternWithDayOfWeek,
            };

            DateTime parsedDateTime;

            if (DateTime.TryParseExact(date, standardFormats, cultureInfo, DateTimeStyles.None, out parsedDateTime))
            {
                result          = new CuiDate(parsedDateTime);
                result.DateType = (approxIndicatorPresent ? DateType.Approximate : DateType.Exact);
                return(true);
            }

            // Check if 'date' is a year and a month
            Regex yearMonthRegEx = BuildMonthYearRegEx(cultureInfo);
            Match yearMonthMatch = yearMonthRegEx.Match(date);

            // Regex doesn't take care of year as zero
            if (yearMonthMatch.Success && CuiDate.ParseYear(yearMonthMatch.Groups["Year"].Value, cultureInfo) > 0)
            {
                int month = GetMonthNumberFromMonthName(yearMonthMatch.Groups["Month"].Value, cultureInfo);
                int year  = CuiDate.ParseYear(yearMonthMatch.Groups["Year"].Value, cultureInfo);
                result = new CuiDate(year, month);
                return(true);
            }

            // Check if 'date' is a year
            Regex yearRegEx = new Regex(@"^(\d{4}|\d{2})$");

            // Regex doesn't take care of year as zero
            if (yearRegEx.IsMatch(date) && CuiDate.ParseYear(date, cultureInfo) > 0)
            {
                result = new CuiDate(CuiDate.ParseYear(date, cultureInfo));
                return(true);
            }

            // Check if 'date' is a Null date
            Regex nullDateRegEx = new Regex(@"^Null:(?<Index>-?\d+)$", RegexOptions.IgnoreCase);

            Match match = nullDateRegEx.Match(date);

            if (match.Success)
            {
                // Pull the numeric Index text and see if it is in range
                int nullIndex;

                if (int.TryParse(match.Groups[1].Captures[0].Value, out nullIndex))
                {
                    if (nullIndex >= MinimumNullIndex && nullIndex <= MaximumNullIndex)
                    {
                        result           = new CuiDate();
                        result.NullIndex = nullIndex;
                        result.DateType  = DateType.NullIndex;

                        return(true);
                    }
                }
            }

            // try alternative formats
            string[] alternativeFormats = new string[]
            {
                "d-MMM-yyyy", "d-M-yyyy", "d-MM-yyyy", "d-MMMM-yyyy",
                "d/MMM/yyyy", "d/M/yyyy", "d/MM/yyyy", "d/MMMM/yyyy",
                "d MMM yyyy", "d M yyyy", "d MM yyyy", "d MMMM yyyy",
                "ddd d-MMM-yyyy", "ddd d-M-yyyy", "ddd d-MM-yyyy", "ddd d-MMMM-yyyy",
                "ddd d/MMM/yyyy", "ddd d/M/yyyy", "ddd d/MM/yyyy", "ddd d/MMMM/yyyy",
                "ddd d MMM yyyy", "ddd d M yyyy", "ddd d MM yyyy", "ddd d MMMM yyyy",
                "d-MMM-yy", "d-M-yy", "d-MM-yy", "d-MMMM-yy",
                "d/MMM/yy", "d/M/yy", "d/MM/yy", "d/MMMM/yy",
                "d MMM yy", "d M yy", "d MM yy", "d MMMM yy",
                "ddd d-MMM-yy", "ddd d-M-yy", "ddd d-MM-yy", "ddd d-MMMM-yy",
                "ddd d/MMM/yy", "ddd d/M/yy", "ddd d/MM/yy", "ddd d/MMMM/yy",
                "ddd d MMM yy", "ddd d M yy", "ddd d MM yy", "ddd d MMMM yy"
            };

            if (DateTime.TryParseExact(date, alternativeFormats, cultureInfo, DateTimeStyles.None, out parsedDateTime))
            {
                result          = new CuiDate(parsedDateTime);
                result.DateType = (approxIndicatorPresent ? DateType.Approximate : DateType.Exact);
                return(true);
            }

            // no match
            result = null;
            return(false);
        }