/// <summary> /// Formats the specified DateTime to a time string representation. /// </summary> /// <param name="value">The DateTime that should be formatted.</param> /// <param name="timeFormat">The time format used to describe how value /// should be formatted.</param> /// <param name="timeCharacters">The allowed characters in the format. /// Leave empty to indicate that all characters are allowed. See remarks.</param> /// <returns> /// A string that represents the time part of a DateTime. /// </returns> /// <remarks>The TimeFormat will contain TimeCharacters in a certain /// order, like hh:mm:ss. By passing specific TimeCharacters, these /// will get filtered and the method only returns part of the formatted /// string. Example: pass 'h', 't', 'H' to get back 4 AM, if the culture /// was set to en-US.</remarks> public virtual string FormatTime(DateTime?value, ITimeFormat timeFormat, params char[] timeCharacters) { if (value.HasValue) { if (timeFormat == null) { throw new ArgumentNullException("timeFormat"); } if (timeCharacters.Count() > 0) { // if timeCharacters is used, only allow those characters. string filtered = new string(timeFormat.GetTimeDisplayFormat(ActualCulture) .ToCharArray() .Where(c => timeCharacters.Contains(c)) .Select(c => c) .ToArray()); // empty timeformat defaults to long datestring, // not filtering is a better default. if (!string.IsNullOrEmpty(filtered)) { timeFormat = new CustomTimeFormat(filtered); } } string formatted = value.Value.ToString(GetTransformedFormat(timeFormat.GetTimeDisplayFormat(ActualCulture)), ActualCulture); // after formatting, allow globalization step to map digits. return(new string(formatted.ToCharArray() .Select(c => Char.IsDigit(c) ? MapDigitToCharacter(Int32.Parse(c.ToString(CultureInfo.InvariantCulture), NumberStyles.Number, CultureInfo.InvariantCulture)) : c) .ToArray()) .Trim()); } return(string.Empty); }
public void ThenTheClockInMidnightShouldLookLike(string theExpectedBerlinClockOutput = "YRRRRRRRROOOOOOOOOOOOOOO") { TimeFormatCreator factory = new ConcereteTimeFormatCreator(); ITimeFormat inputFormat = factory.SetTimeFormat("1"); Time inputTime = inputFormat.SetInput("24:00:00"); String outputTimeFormat = "2"; ITimeFormat outputFormat = factory.GetTimeFormat(outputTimeFormat); Assert.IsNotNull(outputFormat.ToString().Replace(" ", ""), theExpectedBerlinClockOutput); }
/// <summary> /// FormatProperty property changed handler. /// </summary> /// <param name="d">TimePickerPopup that changed its Format.</param> /// <param name="e">Event arguments.</param> private static void OnFormatPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { TimePickerPopup source = (TimePickerPopup)d; ITimeFormat value = e.NewValue as ITimeFormat; // potentially flow back to parent. if (source.TimePickerParent != null && source.TimePickerParent.Format != value) { source.TimePickerParent.SetValue(TimePicker.FormatProperty, value); } if (e.NewValue != null) { // no need for cache any more. source._actualFormat = null; } source.OnFormatChanged(e.OldValue as ITimeFormat, value); }
/// <summary> /// Parses a string into a DateTime using the specified ITimeFormat instance /// and TimeParsers. /// </summary> /// <param name="mappedText">The text that was entered by the user.</param> /// <param name="timeFormat">The TimeFormat instance used to supply /// formats.</param> /// <param name="timeParsers">The time parsers.</param> /// <returns> /// A DateTime with a correctly set time part. /// </returns> /// <remarks>The date part of the DateTime is irrelevant and will be /// overwritten by the current date. /// </remarks> public DateTime?ParseTime(string mappedText, ITimeFormat timeFormat, IEnumerable <TimeParser> timeParsers) { // will perform same logic as TryParse, but will possibly throw. if (timeFormat == null) { throw new ArgumentNullException("timeFormat"); } DateTime?result; if (TryParseTime(mappedText, timeFormat, timeParsers, out result)) { return(result); } // throw exception string message = string.Format( CultureInfo.InvariantCulture, Properties.Resources.UpDown_ParseException, mappedText); throw new ArgumentException(message, "mappedText"); }
public static void Main(string[] args) { TimeFormatCreator factory = new ConcereteTimeFormatCreator(); try { Console.WriteLine("Input Format Type: 1. Simple(hh:mm:ss) "); String inputTimeFormat = Console.ReadLine(); ITimeFormat inputFormat = factory.SetTimeFormat(inputTimeFormat); try { Console.WriteLine("Enter Time:"); String t = Console.ReadLine(); Time inputTime = inputFormat.SetInput(t); try { Console.WriteLine("Output Format Type:\n 1. Default \n2. BerlinClock"); String outputTimeFormat = Console.ReadLine(); ITimeFormat outputFormat = factory.GetTimeFormat(outputTimeFormat); Console.WriteLine("\nOutput Time:"); Console.WriteLine(outputFormat.GetOutput(inputTime)); } catch (Exception eee) { Console.WriteLine(eee.Message); } } catch (Exception ee) { Console.WriteLine(ee.Message); } } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// Parses a string into a DateTime using the specified ITimeFormat instance /// and TimeParsers and returns a value that indicates whether the conversion /// succeeded. /// </summary> /// <param name="mappedText">The text that was entered by the user.</param> /// <param name="timeFormat">The TimeFormat instance used to supply /// formats.</param> /// <param name="timeParsers">The time parsers.</param> /// <param name="result">A DateTime with a correctly set time part.</param> /// <returns> /// True, if the time was parsed correctly, false if the time was not /// parsed. /// </returns> /// <remarks>The date part of the DateTime is irrelevant and will be /// overwritten by the current date. /// </remarks> public bool TryParseTime(string mappedText, ITimeFormat timeFormat, IEnumerable <TimeParser> timeParsers, out DateTime?result) { result = null; if (string.IsNullOrEmpty(mappedText)) { return(true); } string value = new string(mappedText.ToCharArray().Select(c => TimeSeparators.Contains(c) ? c : MapCharacterToDigit(c)).ToArray()); if (timeFormat != null) { DateTime realResult; // try using formats. if (DateTime.TryParseExact( value, timeFormat.GetTimeParseFormats(ActualCulture).Select(s => GetTransformedFormat(s)).ToArray(), ActualCulture, DateTimeStyles.None, out realResult)) { result = realResult; return(true); } } // try using custom collection of parsers. TimeParserCollection timeParserCollection = new TimeParserCollection(GetActualTimeParsers(timeParsers)); DateTime? parsedResult; if (timeParserCollection.TryParse(mappedText, ActualCulture, out parsedResult)) { result = parsedResult; return(true); } return(false); }
public virtual TimeSpan GetTimeUnitAtTextPosition(string text, int textPosition, ITimeFormat timeFormat) { // validate if (string.IsNullOrEmpty(text) || textPosition < 0 || textPosition > text.Length) { return new TimeSpan(); } if (timeFormat == null) { throw new ArgumentNullException("timeFormat"); } // the position that is taken into account is always the // character that comes after the caret. If we are at the // end of the text, we will want to parse the character // before. // if the caret is currently at a timeseperator (:, or .) // also use the previous character. if (textPosition == text.Length || TimeSeparators.Contains(text[textPosition])) { // act on character before return GetTimeUnitAtTextPosition(text, (textPosition - 1), timeFormat); } // if the caret is at a whitespace, look around for the first real character if (Char.IsWhiteSpace(text[textPosition])) { int offset = 1; while (textPosition + offset < text.Length || textPosition - offset >= 0) { if (textPosition - offset >= 0 && !Char.IsWhiteSpace(text[textPosition - offset])) { return GetTimeUnitAtTextPosition(text, textPosition - offset, timeFormat); } if (textPosition + offset < text.Length && !Char.IsWhiteSpace(text[textPosition + offset])) { return GetTimeUnitAtTextPosition(text, textPosition + offset, timeFormat); } offset++; } } #region handle am/pm flip and return // find out information about usage of AM/PM int designatorStartIndex = GetDesignatorTextPositionStart(text); int designatorEndIndex = GetDesignatorTextPositionEnd(text, designatorStartIndex); if (textPosition >= designatorStartIndex && textPosition < designatorEndIndex) { return TimeSpan.FromHours(12); } #endregion // find out the timespan that the spin has effect on // by clearing all the numbers (set to 0) and only setting to 1 // at the caretposition. The remaining timespan can be used to // determine how to increment. StringBuilder timeSpanBuilder = new StringBuilder(text.Length); #region Determine timespan for (int i = 0; i < text.Length; i++) { char c = text[i]; // fill with 0 timeSpanBuilder.Append('0'); // set a 1 timeSpanBuilder[i] = i == textPosition ? '1' : '0'; // copy over separator if (TimeSeparators.Contains(c)) { timeSpanBuilder[i] = c; } // copy over designator if (i >= designatorStartIndex && i < designatorEndIndex) { timeSpanBuilder[i] = c; } // retain white space if (char.IsWhiteSpace(c)) { timeSpanBuilder[i] = c; } } #endregion string NulledTimeAM = timeSpanBuilder.ToString(); if (!string.IsNullOrEmpty(PMDesignator)) { NulledTimeAM = NulledTimeAM.Replace(PMDesignator, AMDesignator); } DateTime? spinnedTime; if (TryParseTime(NulledTimeAM, timeFormat, null, out spinnedTime) && spinnedTime.HasValue) { // behavior is special for hours. // we do not do contextual spinning on the hours, since this // turns out to be too confusing. if (spinnedTime.Value.TimeOfDay.Hours == 10) { return TimeSpan.FromHours(1); } return spinnedTime.Value.TimeOfDay; } else { return new TimeSpan(); } }
/// <summary> /// Parses a string into a DateTime using the specified ITimeFormat instance /// and TimeParsers and returns a value that indicates whether the conversion /// succeeded. /// </summary> /// <param name="mappedText">The text that was entered by the user.</param> /// <param name="timeFormat">The TimeFormat instance used to supply /// formats.</param> /// <param name="timeParsers">The time parsers.</param> /// <param name="result">A DateTime with a correctly set time part.</param> /// <returns> /// True, if the time was parsed correctly, false if the time was not /// parsed. /// </returns> /// <remarks>The date part of the DateTime is irrelevant and will be /// overwritten by the current date. /// </remarks> public bool TryParseTime(string mappedText, ITimeFormat timeFormat, IEnumerable<TimeParser> timeParsers, out DateTime? result) { result = null; if (string.IsNullOrEmpty(mappedText)) { return true; } string value = new string(mappedText.ToCharArray().Select(c => TimeSeparators.Contains(c) ? c : MapCharacterToDigit(c)).ToArray()); if (timeFormat != null) { DateTime realResult; // try using formats. if (DateTime.TryParseExact( value, timeFormat.GetTimeParseFormats(ActualCulture).Select(s => GetTransformedFormat(s)).ToArray(), ActualCulture, DateTimeStyles.None, out realResult)) { result = realResult; return true; } } // try using custom collection of parsers. TimeParserCollection timeParserCollection = new TimeParserCollection(GetActualTimeParsers(timeParsers)); DateTime? parsedResult; if (timeParserCollection.TryParse(mappedText, ActualCulture, out parsedResult)) { result = parsedResult; return true; } return false; }
/// <summary> /// Parses a string into a DateTime using the specified ITimeFormat instance /// and TimeParsers. /// </summary> /// <param name="mappedText">The text that was entered by the user.</param> /// <param name="timeFormat">The TimeFormat instance used to supply /// formats.</param> /// <param name="timeParsers">The time parsers.</param> /// <returns> /// A DateTime with a correctly set time part. /// </returns> /// <remarks>The date part of the DateTime is irrelevant and will be /// overwritten by the current date. /// </remarks> public DateTime? ParseTime(string mappedText, ITimeFormat timeFormat, IEnumerable<TimeParser> timeParsers) { // will perform same logic as TryParse, but will possibly throw. if (timeFormat == null) { throw new ArgumentNullException("timeFormat"); } DateTime? result; if (TryParseTime(mappedText, timeFormat, timeParsers, out result)) { return result; } // throw exception string message = string.Format( CultureInfo.InvariantCulture, Properties.Resources.UpDown_ParseException, mappedText); throw new ArgumentException(message, "mappedText"); }
/// <summary> /// Formats the specified DateTime to a time string representation. /// </summary> /// <param name="value">The DateTime that should be formatted.</param> /// <param name="timeFormat">The time format used to describe how value /// should be formatted.</param> /// <param name="timeCharacters">The allowed characters in the format. /// Leave empty to indicate that all characters are allowed. See remarks.</param> /// <returns> /// A string that represents the time part of a DateTime. /// </returns> /// <remarks>The TimeFormat will contain TimeCharacters in a certain /// order, like hh:mm:ss. By passing specific TimeCharacters, these /// will get filtered and the method only returns part of the formatted /// string. Example: pass 'h', 't', 'H' to get back 4 AM, if the culture /// was set to en-US.</remarks> public virtual string FormatTime(DateTime? value, ITimeFormat timeFormat, params char[] timeCharacters) { if (value.HasValue) { if (timeFormat == null) { throw new ArgumentNullException("timeFormat"); } if (timeCharacters.Count() > 0) { // if timeCharacters is used, only allow those characters. string filtered = new string(timeFormat.GetTimeDisplayFormat(ActualCulture) .ToCharArray() .Where(c => timeCharacters.Contains(c)) .Select(c => c) .ToArray()); // empty timeformat defaults to long datestring, // not filtering is a better default. if (!string.IsNullOrEmpty(filtered)) { timeFormat = new CustomTimeFormat(filtered); } } string formatted = value.Value.ToString(GetTransformedFormat(timeFormat.GetTimeDisplayFormat(ActualCulture)), ActualCulture); // after formatting, allow globalization step to map digits. return new string(formatted.ToCharArray() .Select(c => Char.IsDigit(c) ? MapDigitToCharacter(Int32.Parse(c.ToString(CultureInfo.InvariantCulture), NumberStyles.Number, CultureInfo.InvariantCulture)) : c) .ToArray()) .Trim(); } return string.Empty; }
/// <summary> /// Gets the position for a time unit in a string that can be parsed by /// the specified ITimeFormat. /// </summary> /// <param name="text">The text that represents a DateTime.</param> /// <param name="timeSpan">The time span that is searched for.</param> /// <param name="timeFormat">The time format that describes how this text can be /// parsed to a DateTime.</param> /// <returns> /// The position in the text that corresponds to the TimeSpan or /// -1 if none was found. /// </returns> public virtual int GetTextPositionForTimeUnit(string text, TimeSpan timeSpan, ITimeFormat timeFormat) { if (string.IsNullOrEmpty(text)) { return(-1); } int designatorStartIndex = GetDesignatorTextPositionStart(text); int designatorEndIndex = GetDesignatorTextPositionEnd(text, designatorStartIndex); if (timeSpan == TimeSpan.FromHours(12)) { return(designatorStartIndex); } for (int i = 0; i < text.Length; i++) { if (i > designatorStartIndex && i < designatorEndIndex) { continue; } char c = text[i]; if (Char.IsWhiteSpace(c) || TimeSeparators.Contains(c)) { continue; } if (timeSpan == GetTimeUnitAtTextPosition(text, i, timeFormat)) { return(i); } } return(-1); }
public virtual TimeSpan GetTimeUnitAtTextPosition(string text, int textPosition, ITimeFormat timeFormat) { // validate if (string.IsNullOrEmpty(text) || textPosition < 0 || textPosition > text.Length) { return(new TimeSpan()); } if (timeFormat == null) { throw new ArgumentNullException("timeFormat"); } // the position that is taken into account is always the // character that comes after the caret. If we are at the // end of the text, we will want to parse the character // before. // if the caret is currently at a timeseperator (:, or .) // also use the previous character. if (textPosition == text.Length || TimeSeparators.Contains(text[textPosition])) { // act on character before return(GetTimeUnitAtTextPosition(text, (textPosition - 1), timeFormat)); } // if the caret is at a whitespace, look around for the first real character if (Char.IsWhiteSpace(text[textPosition])) { int offset = 1; while (textPosition + offset < text.Length || textPosition - offset >= 0) { if (textPosition - offset >= 0 && !Char.IsWhiteSpace(text[textPosition - offset])) { return(GetTimeUnitAtTextPosition(text, textPosition - offset, timeFormat)); } if (textPosition + offset < text.Length && !Char.IsWhiteSpace(text[textPosition + offset])) { return(GetTimeUnitAtTextPosition(text, textPosition + offset, timeFormat)); } offset++; } } #region handle am/pm flip and return // find out information about usage of AM/PM int designatorStartIndex = GetDesignatorTextPositionStart(text); int designatorEndIndex = GetDesignatorTextPositionEnd(text, designatorStartIndex); if (textPosition >= designatorStartIndex && textPosition < designatorEndIndex) { return(TimeSpan.FromHours(12)); } #endregion // find out the timespan that the spin has effect on // by clearing all the numbers (set to 0) and only setting to 1 // at the caretposition. The remaining timespan can be used to // determine how to increment. StringBuilder timeSpanBuilder = new StringBuilder(text.Length); #region Determine timespan for (int i = 0; i < text.Length; i++) { char c = text[i]; // fill with 0 timeSpanBuilder.Append('0'); // set a 1 timeSpanBuilder[i] = i == textPosition ? '1' : '0'; // copy over separator if (TimeSeparators.Contains(c)) { timeSpanBuilder[i] = c; } // copy over designator if (i >= designatorStartIndex && i < designatorEndIndex) { timeSpanBuilder[i] = c; } // retain white space if (char.IsWhiteSpace(c)) { timeSpanBuilder[i] = c; } } #endregion string NulledTimeAM = timeSpanBuilder.ToString(); if (!string.IsNullOrEmpty(PMDesignator)) { NulledTimeAM = NulledTimeAM.Replace(PMDesignator, AMDesignator); } DateTime?spinnedTime; if (TryParseTime(NulledTimeAM, timeFormat, null, out spinnedTime) && spinnedTime.HasValue) { // behavior is special for hours. // we do not do contextual spinning on the hours, since this // turns out to be too confusing. if (spinnedTime.Value.TimeOfDay.Hours == 10) { return(TimeSpan.FromHours(1)); } return(spinnedTime.Value.TimeOfDay); } else { return(new TimeSpan()); } }
/// <summary> /// Called when display format changed. /// </summary> /// <param name="oldValue">The old format.</param> /// <param name="newValue">The new format.</param> protected virtual void OnFormatChanged(ITimeFormat oldValue, ITimeFormat newValue) { }
/// <summary> /// Si la fecha del evento ya paso lo indica y si no ha pasado también. /// </summary> /// <param name="eventEntity">Evento</param> /// <returns></returns> public string CreateMessage(IEventEntity eventEntity, ITimeFormat timeFormat) { TimeSpan timeDifference = DateTimeUtilities.GetTimeDifferencDateToDateActual(eventEntity.DateStart, new DateTime()); return(string.Format("{0} ocurrió hace {1}", eventEntity.Title, timeFormat.GetTimeFormat(timeDifference))); }
/// <summary> /// Gets the position for a time unit in a string that can be parsed by /// the specified ITimeFormat. /// </summary> /// <param name="text">The text that represents a DateTime.</param> /// <param name="timeSpan">The time span that is searched for.</param> /// <param name="timeFormat">The time format that describes how this text can be /// parsed to a DateTime.</param> /// <returns> /// The position in the text that corresponds to the TimeSpan or /// -1 if none was found. /// </returns> public virtual int GetTextPositionForTimeUnit(string text, TimeSpan timeSpan, ITimeFormat timeFormat) { if (string.IsNullOrEmpty(text)) { return -1; } int designatorStartIndex = GetDesignatorTextPositionStart(text); int designatorEndIndex = GetDesignatorTextPositionEnd(text, designatorStartIndex); if (timeSpan == TimeSpan.FromHours(12)) { return designatorStartIndex; } for (int i = 0; i < text.Length; i++) { if (i > designatorStartIndex && i < designatorEndIndex) { continue; } char c = text[i]; if (Char.IsWhiteSpace(c) || TimeSeparators.Contains(c)) { continue; } if (timeSpan == GetTimeUnitAtTextPosition(text, i, timeFormat)) { return i; } } return -1; }
/// <summary> /// Called when format changed. /// </summary> /// <param name="oldValue">The old format.</param> /// <param name="newValue">The new format.</param> protected override void OnFormatChanged(ITimeFormat oldValue, ITimeFormat newValue) { base.OnFormatChanged(oldValue, newValue); RegenerateTimeItems(); }