Code:
/ 4.0 / 4.0 / DEVDIV_TFS / Dev10 / Releases / RTMRel / wpf / src / Framework / System / Windows / Controls / DateTimeHelper.cs / 1305600 / DateTimeHelper.cs
// (c) Copyright Microsoft Corporation. // This source is subject to [###LICENSE_NAME###]. // Please see [###LICENSE_LINK###] for details. // All other rights reserved. using System; using System.Diagnostics; using System.Globalization; namespace System.Windows.Controls { // NOTICE: This date time helper assumes it is working in a Gregorian calendar // If we ever support non Gregorian calendars this class would need to be redesigned internal static class DateTimeHelper { private static System.Globalization.Calendar cal = new GregorianCalendar(); public static DateTime? AddDays(DateTime time, int days) { try { return cal.AddDays(time, days); } catch (System.ArgumentException) { return null; } } public static DateTime? AddMonths(DateTime time, int months) { try { return cal.AddMonths(time, months); } catch (System.ArgumentException) { return null; } } public static DateTime? AddYears(DateTime time, int years) { try { return cal.AddYears(time, years); } catch (System.ArgumentException) { return null; } } public static DateTime? SetYear(DateTime date, int year) { return DateTimeHelper.AddYears(date, year - date.Year); } public static DateTime? SetYearMonth(DateTime date, DateTime yearMonth) { DateTime? target = SetYear(date, yearMonth.Year); if (target.HasValue) { target = DateTimeHelper.AddMonths(target.Value, yearMonth.Month - date.Month); } return target; } public static int CompareDays(DateTime dt1, DateTime dt2) { return DateTime.Compare(DiscardTime(dt1).Value, DiscardTime(dt2).Value); } public static int CompareYearMonth(DateTime dt1, DateTime dt2) { return ((dt1.Year - dt2.Year) * 12) + (dt1.Month - dt2.Month); } public static int DecadeOfDate(DateTime date) { return date.Year - (date.Year % 10); } public static DateTime DiscardDayTime(DateTime d) { return new DateTime(d.Year, d.Month, 1, 0, 0, 0); } public static DateTime? DiscardTime(DateTime? d) { if (d == null) { return null; } return d.Value.Date; } public static int EndOfDecade(DateTime date) { return DecadeOfDate(date) + 9; } public static DateTimeFormatInfo GetCurrentDateFormat() { return GetDateFormat(CultureInfo.CurrentCulture); } internal static CultureInfo GetCulture(FrameworkElement element) { bool hasModifiers; CultureInfo culture; if (element.GetValueSource(FrameworkElement.LanguageProperty, null, out hasModifiers) != BaseValueSourceInternal.Default) { culture = MS.Internal.Text.DynamicPropertyReader.GetCultureInfo(element); } else { culture = CultureInfo.CurrentCulture; } return culture; } internal static DateTimeFormatInfo GetDateFormat(CultureInfo culture) { if (culture.Calendar is GregorianCalendar) { return culture.DateTimeFormat; } else { GregorianCalendar foundCal =null; DateTimeFormatInfo dtfi = null; foreach (System.Globalization.Calendar cal in culture.OptionalCalendars) { if (cal is GregorianCalendar) { // Return the first Gregorian calendar with CalendarType == Localized // Otherwise return the first Gregorian calendar if (foundCal == null) { foundCal = cal as GregorianCalendar; } if (((GregorianCalendar)cal).CalendarType == GregorianCalendarTypes.Localized) { foundCal = cal as GregorianCalendar; break; } } } if (foundCal == null) { // if there are no GregorianCalendars in the OptionalCalendars list, use the invariant dtfi dtfi = ((CultureInfo)CultureInfo.InvariantCulture.Clone()).DateTimeFormat; dtfi.Calendar = new GregorianCalendar(); } else { dtfi = ((CultureInfo)culture.Clone()).DateTimeFormat; dtfi.Calendar = foundCal; } return dtfi; } } // returns if the date is included in the range public static bool InRange(DateTime date, CalendarDateRange range) { return InRange(date, range.Start, range.End); } // returns if the date is included in the range public static bool InRange(DateTime date, DateTime start, DateTime end) { Debug.Assert(DateTime.Compare(start, end) < 1); if (CompareDays(date, start) > -1 && CompareDays(date, end) < 1) { return true; } return false; } public static string ToDayString(DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { result = date.Value.Day.ToString(format); } return result; } // This is specifically for Calendar. It switches which year is at the beginning or end of the string. public static string ToDecadeRangeString(int decade, FrameworkElement fe) { string result = string.Empty; DateTimeFormatInfo format = DateTimeHelper.GetDateFormat(DateTimeHelper.GetCulture(fe)); if (format != null) { bool isRightToLeft = fe.FlowDirection==FlowDirection.RightToLeft; int decadeRight = isRightToLeft?decade:(decade+9); int decadeLeft = isRightToLeft?(decade+9):decade; result = decadeLeft.ToString(format) + "-" + decadeRight.ToString(format); } return result; } public static string ToYearMonthPatternString(DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { result = date.Value.ToString(format.YearMonthPattern, format); } return result; } public static string ToYearString(DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { result = date.Value.Year.ToString(format); } return result; } public static string ToAbbreviatedMonthString( DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { string[] monthNames = format.AbbreviatedMonthNames; if (monthNames != null && monthNames.Length > 0) { result = monthNames[(date.Value.Month - 1) % monthNames.Length]; } } return result; } public static string ToLongDateString(DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { result = date.Value.Date.ToString(format.LongDatePattern, format); } return result; } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved. // (c) Copyright Microsoft Corporation. // This source is subject to [###LICENSE_NAME###]. // Please see [###LICENSE_LINK###] for details. // All other rights reserved. using System; using System.Diagnostics; using System.Globalization; namespace System.Windows.Controls { // NOTICE: This date time helper assumes it is working in a Gregorian calendar // If we ever support non Gregorian calendars this class would need to be redesigned internal static class DateTimeHelper { private static System.Globalization.Calendar cal = new GregorianCalendar(); public static DateTime? AddDays(DateTime time, int days) { try { return cal.AddDays(time, days); } catch (System.ArgumentException) { return null; } } public static DateTime? AddMonths(DateTime time, int months) { try { return cal.AddMonths(time, months); } catch (System.ArgumentException) { return null; } } public static DateTime? AddYears(DateTime time, int years) { try { return cal.AddYears(time, years); } catch (System.ArgumentException) { return null; } } public static DateTime? SetYear(DateTime date, int year) { return DateTimeHelper.AddYears(date, year - date.Year); } public static DateTime? SetYearMonth(DateTime date, DateTime yearMonth) { DateTime? target = SetYear(date, yearMonth.Year); if (target.HasValue) { target = DateTimeHelper.AddMonths(target.Value, yearMonth.Month - date.Month); } return target; } public static int CompareDays(DateTime dt1, DateTime dt2) { return DateTime.Compare(DiscardTime(dt1).Value, DiscardTime(dt2).Value); } public static int CompareYearMonth(DateTime dt1, DateTime dt2) { return ((dt1.Year - dt2.Year) * 12) + (dt1.Month - dt2.Month); } public static int DecadeOfDate(DateTime date) { return date.Year - (date.Year % 10); } public static DateTime DiscardDayTime(DateTime d) { return new DateTime(d.Year, d.Month, 1, 0, 0, 0); } public static DateTime? DiscardTime(DateTime? d) { if (d == null) { return null; } return d.Value.Date; } public static int EndOfDecade(DateTime date) { return DecadeOfDate(date) + 9; } public static DateTimeFormatInfo GetCurrentDateFormat() { return GetDateFormat(CultureInfo.CurrentCulture); } internal static CultureInfo GetCulture(FrameworkElement element) { bool hasModifiers; CultureInfo culture; if (element.GetValueSource(FrameworkElement.LanguageProperty, null, out hasModifiers) != BaseValueSourceInternal.Default) { culture = MS.Internal.Text.DynamicPropertyReader.GetCultureInfo(element); } else { culture = CultureInfo.CurrentCulture; } return culture; } internal static DateTimeFormatInfo GetDateFormat(CultureInfo culture) { if (culture.Calendar is GregorianCalendar) { return culture.DateTimeFormat; } else { GregorianCalendar foundCal =null; DateTimeFormatInfo dtfi = null; foreach (System.Globalization.Calendar cal in culture.OptionalCalendars) { if (cal is GregorianCalendar) { // Return the first Gregorian calendar with CalendarType == Localized // Otherwise return the first Gregorian calendar if (foundCal == null) { foundCal = cal as GregorianCalendar; } if (((GregorianCalendar)cal).CalendarType == GregorianCalendarTypes.Localized) { foundCal = cal as GregorianCalendar; break; } } } if (foundCal == null) { // if there are no GregorianCalendars in the OptionalCalendars list, use the invariant dtfi dtfi = ((CultureInfo)CultureInfo.InvariantCulture.Clone()).DateTimeFormat; dtfi.Calendar = new GregorianCalendar(); } else { dtfi = ((CultureInfo)culture.Clone()).DateTimeFormat; dtfi.Calendar = foundCal; } return dtfi; } } // returns if the date is included in the range public static bool InRange(DateTime date, CalendarDateRange range) { return InRange(date, range.Start, range.End); } // returns if the date is included in the range public static bool InRange(DateTime date, DateTime start, DateTime end) { Debug.Assert(DateTime.Compare(start, end) < 1); if (CompareDays(date, start) > -1 && CompareDays(date, end) < 1) { return true; } return false; } public static string ToDayString(DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { result = date.Value.Day.ToString(format); } return result; } // This is specifically for Calendar. It switches which year is at the beginning or end of the string. public static string ToDecadeRangeString(int decade, FrameworkElement fe) { string result = string.Empty; DateTimeFormatInfo format = DateTimeHelper.GetDateFormat(DateTimeHelper.GetCulture(fe)); if (format != null) { bool isRightToLeft = fe.FlowDirection==FlowDirection.RightToLeft; int decadeRight = isRightToLeft?decade:(decade+9); int decadeLeft = isRightToLeft?(decade+9):decade; result = decadeLeft.ToString(format) + "-" + decadeRight.ToString(format); } return result; } public static string ToYearMonthPatternString(DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { result = date.Value.ToString(format.YearMonthPattern, format); } return result; } public static string ToYearString(DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { result = date.Value.Year.ToString(format); } return result; } public static string ToAbbreviatedMonthString( DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { string[] monthNames = format.AbbreviatedMonthNames; if (monthNames != null && monthNames.Length > 0) { result = monthNames[(date.Value.Month - 1) % monthNames.Length]; } } return result; } public static string ToLongDateString(DateTime? date, CultureInfo culture) { string result = string.Empty; DateTimeFormatInfo format = GetDateFormat(culture); if (date.HasValue && format != null) { result = date.Value.Date.ToString(format.LongDatePattern, format); } return result; } } } // File provided for Reference Use Only by Microsoft Corporation (c) 2007. // Copyright (c) Microsoft Corporation. All rights reserved.
Link Menu
This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- EndpointAddressElementBase.cs
- MultipartIdentifier.cs
- ValidateNames.cs
- ToolStripContentPanel.cs
- DataSourceComponent.cs
- DetailsViewModeEventArgs.cs
- DomainConstraint.cs
- UrlMapping.cs
- ContentPosition.cs
- AssociationSet.cs
- XmlElement.cs
- ButtonBase.cs
- loginstatus.cs
- PageThemeBuildProvider.cs
- GacUtil.cs
- RectIndependentAnimationStorage.cs
- ConnectivityStatus.cs
- SingleObjectCollection.cs
- FixedSOMTableCell.cs
- ChannelManager.cs
- AutomationElementCollection.cs
- ConnectionStringSettings.cs
- XPathAxisIterator.cs
- XmlRawWriter.cs
- RecordBuilder.cs
- ElementHostAutomationPeer.cs
- Array.cs
- TextBoxLine.cs
- InstanceHandleReference.cs
- lengthconverter.cs
- HealthMonitoringSectionHelper.cs
- ReferencedAssembly.cs
- SQLDateTimeStorage.cs
- FormViewPagerRow.cs
- EventItfInfo.cs
- ToolStripItemRenderEventArgs.cs
- XmlDataLoader.cs
- NavigationWindowAutomationPeer.cs
- WindowsComboBox.cs
- WebPartUtil.cs
- MemoryFailPoint.cs
- XmlJsonReader.cs
- OrderPreservingPipeliningSpoolingTask.cs
- RequestStatusBarUpdateEventArgs.cs
- StateWorkerRequest.cs
- QuaternionConverter.cs
- ChangeConflicts.cs
- TableLayoutStyle.cs
- newinstructionaction.cs
- _NegoState.cs
- SudsWriter.cs
- webeventbuffer.cs
- PanelDesigner.cs
- EnvironmentPermission.cs
- CriticalFinalizerObject.cs
- XmlSchemaAny.cs
- PropertyEmitter.cs
- MemberJoinTreeNode.cs
- PrintPageEvent.cs
- SectionVisual.cs
- ThreadAbortException.cs
- FileUpload.cs
- DefaultEventAttribute.cs
- ConstraintCollection.cs
- PointLightBase.cs
- PrimaryKeyTypeConverter.cs
- DoneReceivingAsyncResult.cs
- TablePattern.cs
- HttpResponseInternalWrapper.cs
- TraceRecords.cs
- WebContentFormatHelper.cs
- TypefaceMetricsCache.cs
- EpmSourceTree.cs
- OrderPreservingSpoolingTask.cs
- ListManagerBindingsCollection.cs
- EventListenerClientSide.cs
- ReachDocumentReferenceCollectionSerializerAsync.cs
- LambdaCompiler.Address.cs
- HttpRuntime.cs
- SystemParameters.cs
- OutputScopeManager.cs
- FormParameter.cs
- StylusPointCollection.cs
- UrlMappingsSection.cs
- Tokenizer.cs
- Substitution.cs
- ServiceHttpHandlerFactory.cs
- ListViewUpdatedEventArgs.cs
- PlatformCulture.cs
- DbMetaDataCollectionNames.cs
- ResXFileRef.cs
- ResourceManager.cs
- XamlFxTrace.cs
- MyContact.cs
- ExpressionNode.cs
- LogManagementAsyncResult.cs
- MimeXmlReflector.cs
- DPTypeDescriptorContext.cs
- ValueChangedEventManager.cs
- TdsParserStaticMethods.cs