/// <summary> /// Default constructor /// </summary> public MonthCalendarExtender() { this.EnableClientState = true; this.state = new MonthCalendarClientState(); this.value = new NhsDate(); this.value.DateType = DateType.Exact; this.ClientStateValuesLoaded += new EventHandler(this.MonthCalendarExtender_ClientStateValuesLoaded); }
/// <summary> /// Constructs an NhsDate object, uses NhsDate.ParseExact to create a new temporary NhsDate object for the given string /// and copies the property values from the temporary NhsDate object to the new NhsDate object. /// </summary> /// <param name="date">The date.</param> public NhsDate(string date) { NhsDate nd = NhsDate.ParseExact(date, CultureInfo.InvariantCulture); this.DateValue = nd.DateValue; this.DateType = nd.DateType; this.Month = nd.Month; this.Year = nd.Year; this.NullIndex = nd.NullIndex; }
/// <summary> /// Parses a string that represents a date and returns a corresponding NhsDate object, with the culture /// used to parse the string specified. /// </summary> /// <param name="date">The date to be parsed.</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>A new NhsDate object. </returns> /// <exception cref="System.ArgumentNullException">Date is null. </exception> /// <exception cref="System.FormatException">Date is not in a recognised format.</exception> public static NhsDate ParseExact(string date, CultureInfo cultureInfo) { NhsDate result; if (!NhsDate.TryParseExact(date, out result, cultureInfo)) { throw new FormatException(Resources.NhsDateResources.ParseCalledWithBadFormat); } return(result); }
/// <summary> /// Converts the given object to the type of the converter using the specified context and culture information. /// </summary> /// <param name="context">An ITypeDescriptorContext that provides a format context. </param> /// <param name="culture">CultureInfo culture. </param> /// <param name="value">The Object to be converted. </param> /// <returns>An Object that represents the converted value. </returns> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string stringValue = value as string; if (stringValue != null) { NhsDate date = NhsDate.ParseExact(stringValue, culture); return(date); } return(base.ConvertFrom(context, culture, value)); }
/// <summary> /// Determines whether the add instruction operand has a valid value. /// </summary> /// <param name="value">The string used to check whether the add instruction operand has a valid value. </param> /// <returns>True if the add instruction operand has a valid value; otherwise, false. </returns> /// <remarks> /// The test performed is not dependent on the current setting of <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.DateType">DateType</see>. /// This means true is returned if the operand is valid, even if <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.DateType">DateType</see> is not Exact or Approximate. /// </remarks> public static bool IsAddValid(string value) { if (value == null) { throw new ArgumentNullException("value"); } Regex shortcut = new Regex(NhsDate.ResolveAddInstructionRegExTokens(), RegexOptions.IgnoreCase); Match match = shortcut.Match(value.Replace(" ", string.Empty)); return(match.Success); }
public void ConstructNhsDateDateTimeAndBool() { DateTime baseDateTime = DateTime.Now; NhsDate date = new NhsDate(baseDateTime, false); Assert.IsTrue(date.DateType == DateType.Exact); Assert.IsTrue(date.DateValue == baseDateTime); NhsDate date2 = new NhsDate(baseDateTime, true); Assert.IsTrue(date2.DateType == DateType.Approximate); Assert.IsTrue(date2.DateValue == baseDateTime); }
private void ValueTextBox_Leave(object sender, EventArgs e) { NhsDate date; if (NhsDate.TryParseExact(this.valueTextBox.Text, out date, CultureInfo.CurrentCulture)) { if (date.DateType == DateType.Exact && this.approxCheckbox.Checked) { date.DateType = DateType.Approximate; } this.Value = date; } this.UpdateDisplay(); }
/// <summary> /// Converts the given value object to the specified type /// using the specified context and culture information. /// </summary> /// <param name="context">An ITypeDescriptorContext that provides a format context.</param> /// <param name="culture">A CultureInfo. If a null reference (nothing in Visual Basic) is passed, the current culture is assumed. </param> /// <param name="value">The Object to be converted. </param> /// <param name="destinationType">The Type the value parameter is to be converted to. </param> /// <returns>The Type the value parameter is to be converted to. </returns> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) || destinationType == typeof(InstanceDescriptor)) { NhsDate date = (NhsDate)value; bool dateIsApproximate = (date.DateType == DateType.Approximate); CultureInfo cultureInfo = (culture == null ? CultureInfo.InvariantCulture : culture); string formattedDate = date.ToString(false, dateIsApproximate, false, cultureInfo); if (destinationType == typeof(string)) { return(formattedDate); } ConstructorInfo constructor = typeof(NhsDate).GetConstructor(new Type[] { typeof(string) }); return(new InstanceDescriptor(constructor, new object[] { formattedDate })); } return(base.ConvertTo(context, culture, value, destinationType)); }
/// <summary> /// Default constructor /// </summary> public DateInputBoxExtender() { this.EnableClientState = true; this.state = new DateInputClientState(); this.value = new NhsDate(); this.ClientStateValuesLoaded += new EventHandler(this.DateInputBoxExtender_ClientStateValuesLoaded); }
/// <summary> /// Adds a number of months, weeks, days or years to a date. /// </summary> /// <param name="sourceDate">The date to be added to. </param> /// <param name="instruction">Add instructions such as +2w to add 2 weeks or -3m to subtract 3 months. </param> /// <remarks> /// The operand can be positive or negative; if the operand is not included, it is assumed to be positive. /// </remarks> /// <exception cref="System.ArgumentNullException">If either argument is null. /// </exception> /// <exception cref="System.InvalidOperationException">If <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.DateType">DateType</see> /// is null. </exception> /// <exception cref="System.ArgumentException">If <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.DateType">DateType</see> /// is <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.Year">Year</see> and the unit in the instruction is /// not DateArithmeticResources.YearsUnit. Or if <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.DateType">DateType</see> /// is YearMonth and the unit in the instruction is /// not DateArithmeticResources.YearsUnit or DateArithmeticResources.MonthsUnit. Or if the instruction is not /// of the expected format.</exception> /// <exception cref="NhsCui.Toolkit.DateAndTime.InvalidArithmeticSetException">If the set of letters in /// the DateArithmeticResources is not unique or if values are not each a single character long. /// </exception> /// <returns>A new NhsDate object. </returns> public static NhsDate Add(NhsDate sourceDate, string instruction) { if (instruction == null) { throw new ArgumentNullException("instruction"); } if (sourceDate == null) { throw new ArgumentNullException("sourceDate"); } // check the set of resource strings used by this method are // valid if (!CheckArithmeticSetResources()) { throw new InvalidArithmeticSetException(Resources.NhsDateResources.ArithmeticSetInvalidResources); } if (sourceDate.DateType == DateType.NullIndex) { throw new InvalidOperationException(Resources.NhsDateResources.AddNotAllowedForDateType); } if (NhsDate.IsAddValid(instruction) == false) { throw new ArgumentException(Resources.NhsDateResources.AddInstructionInvalidFormat, "instruction"); } Regex shortcut = new Regex(NhsDate.ResolveAddInstructionRegExTokens(), RegexOptions.IgnoreCase); Match match = shortcut.Match(instruction.Replace(" ", string.Empty)); if (match.Success == true) { // We need to skip the first group because with this RegEx it is always the complete string int groupNumber = 0; foreach (Group g in match.Groups) { if (groupNumber > 0) // Skip first group { foreach (Capture c in g.Captures) { int increment; if (int.TryParse(c.Value.Substring(0, c.Value.Length - 1), out increment)) { if (c.Value.EndsWith(Resources.NhsDateResources.MonthsUnit, StringComparison.OrdinalIgnoreCase) == true) { if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate) { sourceDate.DateValue = sourceDate.DateValue.AddMonths(increment); } else if (sourceDate.DateType == DateType.YearMonth) { sourceDate.Year += increment / 12; sourceDate.Month += increment % 12; } else { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NhsDateResources.AddInstructionNotAllowedForDateType, "Month", sourceDate.DateType), "instruction"); } } else if (c.Value.EndsWith(Resources.NhsDateResources.WeeksUnit, StringComparison.OrdinalIgnoreCase) == true) { if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate) { // Add weeks using AddDays and multiplying number of weeks to add by 7 sourceDate.DateValue = sourceDate.DateValue.AddDays(increment * 7); } else { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NhsDateResources.AddInstructionNotAllowedForDateType, "Week", sourceDate.DateType), "instruction"); } } else if (c.Value.EndsWith(Resources.NhsDateResources.DaysUnit, StringComparison.OrdinalIgnoreCase) == true) { if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate) { sourceDate.DateValue = sourceDate.DateValue.AddDays(increment); } else { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NhsDateResources.AddInstructionNotAllowedForDateType, "Day", sourceDate.DateType), "instruction"); } } else if (c.Value.EndsWith(Resources.NhsDateResources.YearsUnit, StringComparison.OrdinalIgnoreCase) == true) { if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate) { sourceDate.DateValue = sourceDate.DateValue.AddYears(increment); } else if (sourceDate.DateType == DateType.Year || sourceDate.DateType == DateType.YearMonth) { sourceDate.Year += increment; } else { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NhsDateResources.AddInstructionNotAllowedForDateType, "Year", sourceDate.DateType), "instruction"); } } } } } groupNumber++; } } return sourceDate; }
/// <summary> /// Parses a string that represents a date. /// </summary> /// <param name="date">A string containing the value to be parsed. </param> /// <param name="result">A container for a successfully-parsed date. </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 NhsDate 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 NhsDate result) { return NhsDate.TryParseExact(date, out result, CultureInfo.InvariantCulture); }
public void DateOfBirthDayTextMonthYearTest() { Parser target = new Parser(); NhsDate expectedNhsDate = new NhsDate(new DateTime(1960, 4, 15)); target.Text = "May Williams 15-April-1960"; target.Parse(); // Can't check for equivalence using Assert.AreEqual<NhsDate>(expectedNhsDate, target.DateOfBirth) // because NhsDate doesn't override the equality operator so check using ToString() calls... Assert.AreEqual<string>(expectedNhsDate.ToString(), target.DateOfBirth.ToString(), "NhsCui.Toolkit.Parser.DateOfBirth was not set correctly by Parse method."); }
public void ParseCase3Test() { Parser target = new Parser(); NhsDate expectedNhsDate = new NhsDate(1964, 9); target.Text = "John Smith Sept-1964 30"; target.Parse(); Assert.AreEqual<string>("John", target.GivenName, "NhsCui.Toolkit.Parser.GivenName was not set correctly in Parse Case 3."); Assert.AreEqual<string>("Smith", target.FamilyName, "NhsCui.Toolkit.Parser.FamilyName was not set correctly in Parse Case 3."); // Can't check for equivalence using Assert.AreEqual<NhsDate>(expectedNhsDate, target.DateOfBirth) // because NhsDate doesn't override the equality operator so check using ToString() calls... Assert.AreEqual<string>(expectedNhsDate.ToString(), target.DateOfBirth.ToString(), "NhsCui.Toolkit.Parser.Address was not set correctly in Parse Case 3."); Assert.AreEqual<int>(30, target.Age, "NhsCui.Toolkit.Parser.Age was not set correctly in Parse Case 3."); }
public void ParseCase9Test() { Parser target = new Parser(); target.Text = "Mr Smith 1964"; NhsDate expectedNhsDate = new NhsDate(1964); target.Parse(); Assert.AreEqual<Gender>(Gender.Male, target.Gender, "NhsCui.Toolkit.Parser.Gender was not set correctly in Parse Case 9."); Assert.AreEqual<string>("Mr", target.Title, "NhsCui.Toolkit.Parser.Title was not set correctly in Parse Case 9."); Assert.AreEqual<string>("Smith", target.FamilyName, "NhsCui.Toolkit.Parser.FamilyName was not set correctly in Parse Case 9."); // Can't check for equivalence using Assert.AreEqual<NhsDate>(expectedNhsDate, target.DateOfBirth) // because NhsDate doesn't override the equality operator so check using ToString() calls... Assert.AreEqual<string>(expectedNhsDate.ToString(), target.DateOfBirth.ToString(), "NhsCui.Toolkit.Parser.DateOfBirth was not set correctly in Parse Case 9."); }
public void ToStringYear() { System.DateTime baseDateTime = System.DateTime.Now; NhsDate date = new NhsDate(baseDateTime); date.DateType = DateType.Year; Assert.AreEqual("0000", date.ToString(), "Check the default of Year when an explicit date is passed to ctor"); date = new NhsDate(baseDateTime.Year); date.DateType = DateType.Year; Assert.AreEqual(baseDateTime.Year.ToString(CultureInfo.CurrentCulture), date.ToString()); }
public void ToStringYearMonth() { System.DateTime baseDateTime = System.DateTime.Now; NhsDate date = new NhsDate(baseDateTime); date.DateType = DateType.YearMonth; Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "{0}-{1}", CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[1 - 1], "0000"), date.ToString(), "Check the default of Month and Year when an explicit date is passed to ctor"); // Now set the date to a year and a month which is what DateType = YearMonth prefers date = new NhsDate(1974, 3); Assert.AreEqual( string.Format(CultureInfo.InvariantCulture, "{0}-{1}", CultureInfo.CurrentUICulture.DateTimeFormat.MonthNames[3 - 1], "1974"), date.ToString()); }
public void ToStringExact() { NhsDate date = new NhsDate(new System.DateTime(1974, 3, 26)); Assert.AreEqual("26-Mar-1974", date.ToString()); Assert.AreEqual("26-Mar-1974", date.ToString(false), "Check that default for 'include day of week' flag is correct"); // try with includeDayOfWeek flag Assert.AreEqual("Tue 26-Mar-1974", date.ToString(true)); }
public void ToStringExactGetRelativeText() { NhsDate date = new NhsDate(System.DateTime.Today); GlobalizationService gc = new GlobalizationService(); // Today works Assert.AreEqual(NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.Today, date.ToString(false, false, true, CultureInfo.CurrentCulture), "RelativeText of Today is not working"); date.DateValue = DateTime.Today.AddDays(1); Assert.AreEqual(NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.Tomorrow, date.ToString(false, false, true, CultureInfo.CurrentCulture), "RelativeText of Tomorrow is not working"); date.DateValue = DateTime.Today.AddDays(-1); Assert.AreEqual(NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.Yesterday, date.ToString(false, false, true, CultureInfo.CurrentCulture), "RelativeText of Yesterday is not working"); // Check the "Who Wins condition when "Show Day of Week" and "Show Relative Text" are both true Assert.AreEqual(NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.Yesterday, date.ToString(true, false, true, CultureInfo.CurrentCulture), "When includeDayOfWeek, showRelativeText are both true, showRelativeText should win. It is not"); DateTime testDate = new DateTime(1974, 3, 26); date.DateValue = testDate; Assert.AreEqual(testDate.ToString(gc.ShortDatePattern, CultureInfo.CurrentCulture), date.ToString(), "Check that default for 'include day of week' flag is correct"); // try with includeDayOfWeek flag Assert.AreEqual(testDate.ToString(gc.ShortDatePatternWithDayOfWeek, CultureInfo.CurrentCulture), date.ToString(true), "Check that default for 'include day of week' flag is correct"); }
public void DataSubtract2YearsAdd5Days() { DateTime nowAsItWasAtTheStartofTheTest = DateTime.Now; NhsDate date = new NhsDate(nowAsItWasAtTheStartofTheTest); date.Add(string.Format(CultureInfo.CurrentCulture, "-2{0}+5{1}", NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.YearsUnit, NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.DaysUnit)); Assert.AreEqual(nowAsItWasAtTheStartofTheTest.AddYears(-2).AddDays(5), date.DateValue); }
public void DataAdd7Years() { DateTime nowAsItWasAtTheStartofTheTest = DateTime.Now; NhsDate date = new NhsDate(nowAsItWasAtTheStartofTheTest); date.Add(string.Format(CultureInfo.CurrentCulture, "+7{0}", NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.YearsUnit)); Assert.AreEqual(nowAsItWasAtTheStartofTheTest.AddYears(7), date.DateValue); }
public void DataAddMonthAndDay() { DateTime nowAsItWasAtTheStartofTheTest = DateTime.Now; NhsDate date = new NhsDate(nowAsItWasAtTheStartofTheTest); date.Add(string.Format(CultureInfo.CurrentCulture, "+1{0}+1{1}", NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.MonthsUnit, NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.DaysUnit)); Assert.AreEqual(date.DateValue, nowAsItWasAtTheStartofTheTest.AddMonths(1).AddDays(1)); }
/// <summary> /// Handles the selected date changed event of calendar. /// </summary> /// <param name="sender">Object calling the event</param> /// <param name="e">Event arguments</param> private void Calendar_SelectedDateChanged(object sender, DateChangedEventArgs e) { if (this.inlineEditing) { this.inlineEditing = false; return; } if ((e.Changes & ChangedDateParts.YearChanged) != ChangedDateParts.YearChanged && (e.Changes & ChangedDateParts.MonthChanged) != ChangedDateParts.MonthChanged) { if (this.Functionality == DateFunctionality.Complex || ((e.Changes & ChangedDateParts.YearSelected) != ChangedDateParts.YearSelected && (e.Changes & ChangedDateParts.MonthSelected) != ChangedDateParts.MonthSelected && (e.Changes & ChangedDateParts.NullStringSelected) != ChangedDateParts.NullStringSelected)) { this.Value = new NhsDate(e.SelectedDate); if ((e.Changes & ChangedDateParts.YearSelected) == ChangedDateParts.YearSelected) { this.DateType = DateType.Year; this.editingDateType = DateType.Year; this.Year = e.SelectedDate.Year; } else if ((e.Changes & ChangedDateParts.MonthSelected) == ChangedDateParts.MonthSelected) { this.DateType = DateType.YearMonth; this.editingDateType = DateType.YearMonth; this.Year = e.SelectedDate.Year; this.Month = e.SelectedDate.Month; } else if ((e.Changes & ChangedDateParts.NullStringSelected) == ChangedDateParts.NullStringSelected) { this.DateType = DateType.NullIndex; this.editingDateType = DateType.NullIndex; this.NullIndex = this.calendar.NullIndex; } this.calendar.Hide(); this.currentValue = this.Value; this.txtInput.Focus(); this.validated = false; this.FormatOnFocusValue(); } } }
public void ToStringNull() { NhsDate date = new NhsDate(); date.DateType = DateType.Null; Assert.IsTrue(date.ToString().Length == 0); }
/// <summary> /// Adds a number of months, weeks, days or years to a date. /// </summary> /// <param name="instruction">Add instructions such as +2w to add 2 weeks or -3m to subtract 3 months.</param> /// <remarks> /// The operand can be positive or negative; if the operand is not included, it is assumed to be positive. /// </remarks> /// <exception cref="System.ArgumentNullException">Instruction is null.</exception> public void Add(string instruction) { this.DateValue = NhsDate.Add(this, instruction).DateValue; }
public void ParseMonthAndYear() { System.DateTime baseDateTime = System.DateTime.Now; NhsDate date = new NhsDate(baseDateTime); date.DateType = DateType.YearMonth; date.Year = 1974; date.Month = 3; NhsDate parsedDate; Assert.IsTrue(NhsDate.TryParseExact("jan-2008", out parsedDate, CultureInfo.InvariantCulture), "Try parse failed"); Assert.AreEqual(parsedDate.Month, 1, "Month not being parsed"); Assert.AreEqual(parsedDate.Year, 2008, "Month not being parsed"); Assert.IsTrue(NhsDate.TryParseExact("january-2008", out parsedDate, CultureInfo.InvariantCulture), "Try parse failed"); Assert.AreEqual(parsedDate.Month, 1, "Month not being parsed"); Assert.AreEqual(parsedDate.Year, 2008, "Month not being parsed"); Assert.IsTrue(NhsDate.TryParseExact("1-2008", out parsedDate, CultureInfo.InvariantCulture), "Try parse failed"); Assert.AreEqual(parsedDate.Month, 1, "Month not being parsed"); Assert.AreEqual(parsedDate.Year, 2008, "Month not being parsed"); Assert.IsTrue(NhsDate.TryParseExact("10-2008", out parsedDate, CultureInfo.InvariantCulture), "Try parse failed"); Assert.AreEqual(parsedDate.Month, 10, "Month not being parsed"); Assert.AreEqual(parsedDate.Year, 2008, "Month not being parsed"); Assert.IsTrue(NhsDate.TryParseExact(date.ToString(), out parsedDate, CultureInfo.InvariantCulture), string.Format(CultureInfo.InvariantCulture, "TryParse failed with date, {0}", date.ToString())); Assert.AreEqual(date.Month, parsedDate.Month, "Parse did not error but Month does not match"); Assert.AreEqual(date.DateType, parsedDate.DateType, "Parse did not error but DateType does not match"); Assert.AreEqual(date.Year, parsedDate.Year, "Parse did not error but Year does not match"); }
public void ParseCase4Test() { Parser target = new Parser(); NhsDate expectedNhsDate = new NhsDate(1954, 6); target.Text = "May Williams June-1954"; target.Parse(); Assert.AreEqual<string>("May", target.GivenName, "NhsCui.Toolkit.Parser.GivenName was not set correctly in Parse Case 4."); Assert.AreEqual<string>("Williams", target.FamilyName, "NhsCui.Toolkit.Parser.FamilyName was not set correctly in Parse Case 4."); // Can't check for equivalence using Assert.AreEqual<NhsDate>(expectedNhsDate, target.DateOfBirth) // because NhsDate doesn't override the equality operator so check using ToString() calls... Assert.AreEqual<string>(expectedNhsDate.ToString(), target.DateOfBirth.ToString(), "NhsCui.Toolkit.Parser.Address was not set correctly in Parse Case 4."); }
public void ParseNullIndex() { NhsDate date = new NhsDate(); date.DateType = DateType.NullIndex; date.NullIndex = 14; // Muddy the water by assigning Month and year date.Year = 2007; date.Month = 3; NhsDate parsedDate; Assert.IsTrue(NhsDate.TryParseExact(date.ToString(), out parsedDate, CultureInfo.InvariantCulture), string.Format(CultureInfo.InvariantCulture, "TryParse failed with date, {0}", date.ToString())); Assert.AreEqual(date.DateType, parsedDate.DateType, "Parse did not error but DateType does not match"); Assert.AreEqual(date.NullIndex, parsedDate.NullIndex, "Parse did not error but NullIndex does not match"); }
public void ParseCase14Test() { // Extra case to test for the PSIB Sample input string Parser target = new Parser(); NhsDate expectedNhsDate = new NhsDate("18-May-1972"); target.Text = "mr john evans 64 chester str e182ng 34 18/05/1972 1234567890"; target.Parse(); Assert.AreEqual<string>("evans", target.FamilyName, "NhsCui.Toolkit.Parser.FamilyName was not set correctly in Parse Case 14."); Assert.AreEqual<string>("john", target.GivenName, "NhsCui.Toolkit.Parser.GivenName was not set correctly in Parse Case 14."); Assert.AreEqual<string>("1234567890", target.NhsNumber, "NhsCui.Toolkit.Parser.NhsNumber was not set correctly in Parse Case 14."); Assert.AreEqual<int>(34, target.Age, "NhsCui.Toolkit.Parser.Age was not set correctly in Parse Case 14."); Assert.AreEqual<string>(expectedNhsDate.ToString(), target.DateOfBirth.ToString(), "NhsCui.Toolkit.Parser.DateOfBirth was not set correctly in Parse Case 14."); // Can't check for equivalence using Assert.AreEqual<NhsDate>(expectedNhsDate, target.DateOfBirth) // because NhsDate doesn't override the equality operator so check using ToString() calls... Assert.AreEqual<Gender>(Gender.Male, target.Gender, "NhsCui.Toolkit.Parser.Gender was not set correctly in Parse Case 14."); Assert.AreEqual<string>("mr", target.Title, "NhsCui.Toolkit.Parser.Title was not set correctly in Parse Case 14."); Assert.AreEqual<string>("64 chester str", target.Address, "NhsCui.Toolkit.Parser.Address was not set correctly in Parse Case 14."); Assert.AreEqual<string>("e182ng", target.Postcode, "NhsCui.Toolkit.Parser.Postcode was not set correctly in Parse Case 14."); }
public void ParseDateText() { NhsDate date = new NhsDate("26-March-1974"); NhsDate parsedDate; Assert.IsTrue(NhsDate.TryParseExact(date.ToString(), out parsedDate, CultureInfo.InvariantCulture), string.Format(CultureInfo.InvariantCulture, "TryParse failed with date, {0}", date.ToString())); Assert.AreEqual(date.DateType, parsedDate.DateType, "Parse did not error but DateType does not match"); Assert.AreEqual(date.DateValue, parsedDate.DateValue, "Parse did not error but DateValue does not match"); }
public void DateOfBirthUpperTest() { Parser target = new Parser(); NhsDate expectedNhsDate = new NhsDate(1954, 7); target.Text = "May Williams June-1954-July-1954"; target.Parse(); // Can't check for equivalence using Assert.AreEqual<NhsDate>(expectedNhsDate, target.DateOfBirth) // because NhsDate doesn't override the equality operator so check using ToString() calls... Assert.AreEqual<string>(expectedNhsDate.ToString(), target.DateOfBirthUpper.ToString(), "NhsCui.Toolkit.Parser.DateOfBirthUpper was not set correctly by Parse method."); }
/// <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 NhsDate 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 NhsDate result, CultureInfo cultureInfo) { // check for true null if (string.IsNullOrEmpty(date)) { result = new NhsDate(); 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 NhsDate(); result.DateType = DateType.YearMonth; result.Month = int.Parse(numericYearMonthRegExResults.Groups["Month"].Value, cultureInfo); result.Year = NhsDate.ParseYear(numericYearMonthRegExResults.Groups["Year"].Value, cultureInfo); return(true); } // check to see if approx indicator is present bool approxIndicatorPresent = (date.IndexOf(Resources.NhsDateResources.Approximate, StringComparison.CurrentCultureIgnoreCase) >= 0); if (approxIndicatorPresent) { date = date.Replace(Resources.NhsDateResources.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 NhsDate(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 && NhsDate.ParseYear(yearMonthMatch.Groups["Year"].Value, cultureInfo) > 0) { int month = GetMonthNumberFromMonthName(yearMonthMatch.Groups["Month"].Value, cultureInfo); int year = NhsDate.ParseYear(yearMonthMatch.Groups["Year"].Value, cultureInfo); result = new NhsDate(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) && NhsDate.ParseYear(date, cultureInfo) > 0) { result = new NhsDate(NhsDate.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 NhsDate(); 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 NhsDate(parsedDateTime); result.DateType = (approxIndicatorPresent ? DateType.Approximate : DateType.Exact); return(true); } // no match result = null; return(false); }
/// <summary> /// Parses a string that represents a date and returns a corresponding NhsDate object. /// </summary> /// <param name="date">The date to be parsed. </param> /// <returns>A new NhsDate object. </returns> /// <exception cref="System.ArgumentNullException">Date is null. </exception> /// <exception cref="System.FormatException">Date is not in a recognised format. </exception> public static NhsDate ParseExact(string date) { return(NhsDate.ParseExact(date, CultureInfo.CurrentCulture)); }
/// <summary> /// Parses a string that represents a date. /// </summary> /// <param name="date">A string containing the value to be parsed. </param> /// <param name="result">A container for a successfully-parsed date. </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 NhsDate 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 NhsDate result) { return(NhsDate.TryParseExact(date, out result, CultureInfo.InvariantCulture)); }
/// <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 NhsDate 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 NhsDate result, CultureInfo cultureInfo) { // check for true null if (string.IsNullOrEmpty(date)) { result = new NhsDate(); 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 NhsDate(); result.DateType = DateType.YearMonth; result.Month = int.Parse(numericYearMonthRegExResults.Groups["Month"].Value, cultureInfo); result.Year = NhsDate.ParseYear(numericYearMonthRegExResults.Groups["Year"].Value, cultureInfo); return true; } // check to see if approx indicator is present bool approxIndicatorPresent = (date.IndexOf(Resources.NhsDateResources.Approximate, StringComparison.CurrentCultureIgnoreCase) >= 0); if (approxIndicatorPresent) { date = date.Replace(Resources.NhsDateResources.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 NhsDate(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 && NhsDate.ParseYear(yearMonthMatch.Groups["Year"].Value, cultureInfo) > 0) { int month = GetMonthNumberFromMonthName(yearMonthMatch.Groups["Month"].Value, cultureInfo); int year = NhsDate.ParseYear(yearMonthMatch.Groups["Year"].Value, cultureInfo); result = new NhsDate(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) && NhsDate.ParseYear(date, cultureInfo) > 0) { result = new NhsDate(NhsDate.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 NhsDate(); 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 NhsDate(parsedDateTime); result.DateType = (approxIndicatorPresent ? DateType.Approximate : DateType.Exact); return true; } // no match result = null; return false; }
public void NullInstructionAddTest() { DateTime nowAsItWasAtTheStartofTheTest = DateTime.Now; NhsDate date = new NhsDate(nowAsItWasAtTheStartofTheTest); NhsDate.Add(date, null); }
/// <summary> /// Handle loading of client state /// </summary> /// <param name="sender">sender</param> /// <param name="e">args</param> private void DateInputBoxExtender_ClientStateValuesLoaded(object sender, EventArgs e) { if (this.ClientState != null) { JavaScriptSerializer jss = new JavaScriptSerializer(); jss.RegisterConverters(new JavaScriptConverter[] { new NhsDateJavascriptConverter() }); this.state = jss.Deserialize<DateInputClientState>(ClientState); this.value = this.state.Value; this.calendarPosition = this.state.CalendarPosition; } }
public void InvalidInstructionAddTest() { DateTime date = DateTime.Now; NhsDate sourcedate = new NhsDate(date); NhsDate.Add(sourcedate, string.Format(CultureInfo.CurrentCulture, "+1{0}", NhsCui.Toolkit.Test.NhsCui_Toolkit_DateAndTime_Resources_NhsDateResourcesAccessor.resourceCulture)); }
/// <summary> /// Resets the control's state fields to their default value. /// </summary> private void ResetFields() { this.SetDefaultField(); this.currentMode = InputMode.Simple; this.currentValue = this.Value; this.editingDateType = this.DateType; if ((this.editingDateType == DateType.Approximate || this.editingDateType == DateType.Exact) && !this.IsCorrectFormatForExactDate()) { this.invalidFormat = true; } else { this.invalidFormat = false; } this.LoadResources(); this.SelectCurrentField(); }
private void ValueTextBox_Leave(object sender, EventArgs e) { NhsDate date; if (NhsDate.TryParseExact(this.valueTextBox.Text, out date, CultureInfo.CurrentCulture)) { if (date.DateType == DateType.Exact && this.approxCheckbox.Checked) { date.DateType = DateType.Approximate; } this.Value = date; } this.UpdateDisplay(); }
public void IsNullProperty() { NhsDate date = new NhsDate(); // default datetype is exact Assert.IsFalse(date.IsNull); date.DateType = DateType.Null; Assert.IsTrue(date.IsNull); }
/// <summary> /// Adds a number of months, weeks, days or years to a date. /// </summary> /// <param name="sourceDate">The date to be added to. </param> /// <param name="instruction">Add instructions such as +2w to add 2 weeks or -3m to subtract 3 months. </param> /// <remarks> /// The operand can be positive or negative; if the operand is not included, it is assumed to be positive. /// </remarks> /// <exception cref="System.ArgumentNullException">If either argument is null. /// </exception> /// <exception cref="System.InvalidOperationException">If <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.DateType">DateType</see> /// is null. </exception> /// <exception cref="System.ArgumentException">If <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.DateType">DateType</see> /// is <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.Year">Year</see> and the unit in the instruction is /// not DateArithmeticResources.YearsUnit. Or if <see cref="P:NhsCui.Toolkit.DateAndTime.NhsDate.DateType">DateType</see> /// is YearMonth and the unit in the instruction is /// not DateArithmeticResources.YearsUnit or DateArithmeticResources.MonthsUnit. Or if the instruction is not /// of the expected format.</exception> /// <exception cref="NhsCui.Toolkit.DateAndTime.InvalidArithmeticSetException">If the set of letters in /// the DateArithmeticResources is not unique or if values are not each a single character long. /// </exception> /// <returns>A new NhsDate object. </returns> public static NhsDate Add(NhsDate sourceDate, string instruction) { if (instruction == null) { throw new ArgumentNullException("instruction"); } if (sourceDate == null) { throw new ArgumentNullException("sourceDate"); } // check the set of resource strings used by this method are // valid if (!CheckArithmeticSetResources()) { throw new InvalidArithmeticSetException(Resources.NhsDateResources.ArithmeticSetInvalidResources); } if (sourceDate.DateType == DateType.NullIndex) { throw new InvalidOperationException(Resources.NhsDateResources.AddNotAllowedForDateType); } if (NhsDate.IsAddValid(instruction) == false) { throw new ArgumentException(Resources.NhsDateResources.AddInstructionInvalidFormat, "instruction"); } Regex shortcut = new Regex(NhsDate.ResolveAddInstructionRegExTokens(), RegexOptions.IgnoreCase); Match match = shortcut.Match(instruction.Replace(" ", string.Empty)); if (match.Success == true) { // We need to skip the first group because with this RegEx it is always the complete string int groupNumber = 0; foreach (Group g in match.Groups) { if (groupNumber > 0) // Skip first group { foreach (Capture c in g.Captures) { int increment; if (int.TryParse(c.Value.Substring(0, c.Value.Length - 1), out increment)) { if (c.Value.EndsWith(Resources.NhsDateResources.MonthsUnit, StringComparison.OrdinalIgnoreCase) == true) { if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate) { sourceDate.DateValue = sourceDate.DateValue.AddMonths(increment); } else if (sourceDate.DateType == DateType.YearMonth) { sourceDate.Year += increment / 12; sourceDate.Month += increment % 12; } else { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NhsDateResources.AddInstructionNotAllowedForDateType, "Month", sourceDate.DateType), "instruction"); } } else if (c.Value.EndsWith(Resources.NhsDateResources.WeeksUnit, StringComparison.OrdinalIgnoreCase) == true) { if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate) { // Add weeks using AddDays and multiplying number of weeks to add by 7 sourceDate.DateValue = sourceDate.DateValue.AddDays(increment * 7); } else { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NhsDateResources.AddInstructionNotAllowedForDateType, "Week", sourceDate.DateType), "instruction"); } } else if (c.Value.EndsWith(Resources.NhsDateResources.DaysUnit, StringComparison.OrdinalIgnoreCase) == true) { if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate) { sourceDate.DateValue = sourceDate.DateValue.AddDays(increment); } else { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NhsDateResources.AddInstructionNotAllowedForDateType, "Day", sourceDate.DateType), "instruction"); } } else if (c.Value.EndsWith(Resources.NhsDateResources.YearsUnit, StringComparison.OrdinalIgnoreCase) == true) { if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate) { sourceDate.DateValue = sourceDate.DateValue.AddYears(increment); } else if (sourceDate.DateType == DateType.Year || sourceDate.DateType == DateType.YearMonth) { sourceDate.Year += increment; } else { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.NhsDateResources.AddInstructionNotAllowedForDateType, "Year", sourceDate.DateType), "instruction"); } } } } } groupNumber++; } } return(sourceDate); }