我正在尝试将日期或月份添加到日期时间。决定应该在日期时间中增加天数还是月份的因素是dayOrMonth的结束日期。因此,例如,如果dayOrMonth以MM结尾,则应添加月份,如果以DD结尾,则应添加天。
dayOrMonth可能看起来像这样的“ 90DD”(应添加90天),“ 90MM”应添加90个月。
我正在考虑创建某种扩展方法,但是我为此付出了很多努力,因为如果不能使用语句则添加更多。
//... Set payment dates.
string dayOrMonth;
for (int x = 0; x < installmentDates.Count; x++)
{
if (installmentDates.Count > 0)
{
installmentdDateRow[colName] = installmentdDateRow[colName] + Convert.ToDateTime(installmentDates[x]).ToString("dd'-'MM'-'yyyy") + "\n";
//... Future payment dates.
int futurePaymentColumn = installmentdFuturePayments.Table.Columns.IndexOf(colName);
if (colName == "1. rate" && installmentDates.Count - 1 == x)
{
installmentdFuturePayments[futurePaymentColumn + 1] = installmentdFuturePayments[futurePaymentColumn + 1] + Convert.ToDateTime(installmentDates[x]).AddMonths(3).ToString("dd'-'MM'-'yyyy") + "\n";
}
if (colName == "2. rate" && installmentDates.Count - 1 == x && Functions.GetProductInfo(unit.Key.ToString().Split('-')[0])[9] != "€ 0,00")
{
installmentdFuturePayments[futurePaymentColumn + 1] = installmentdFuturePayments[futurePaymentColumn + 1] + Convert.ToDateTime(installmentDates[x]).AddMonths(3).ToString("dd'-'MM'-'yyyy") + "\n";
}
}
}
答案 0 :(得分:1)
您已经描述了一个由两部分组成的输入字符串:
因此,您知道应该始终至少包含三个字符。您还知道尾随两个字符定义了操作,因此可以使用Substring
将那些字符与字符串的其余部分分开。
扩展方法是一个好主意。它应该包括测试,以帮助强制输入字符串的格式,并使解析数字组件变得容易。
public static DateTime ApplyInput(this DateTime dt, string input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input), "The input string must not be null.");
}
if (input.Length < 3)
{
throw new ArgumentException("The input string is too short to include both a number and an operation.", nameof(input));
}
string numberChars = input.Substring(0, input.Length - 2);
if (!int.TryParse(numberChars, out int number))
{
throw new ArgumentException("The start of the input string must be an integer.", nameof(input));
}
string endingChars = input.Substring(input.Length - 2);
switch (endingChars.ToUpperInvariant())
{
case "MM":
return dt.AddMonths(number);
case "DD":
return dt.AddDays(number);
default:
throw new ArgumentException($"The characters {endingChars} were not recognized as a valid operation.", nameof(input));
}
}
与使用RegEx
,Contains
或Replace
相比,此方法的效果更好。通过向开关添加更多case语句,它也可以扩展。
请注意,.ToUpperInvariant()
使操作字符不区分大小写,因此您可以根据需要传递mm
或dd
。如果您不想这样做,则只需删除.ToUpperInvariant()
。
答案 1 :(得分:0)
使用StackOverflow - Seperating characters and numbers
您可以使用正则表达式将数字与给定字符串中的字符分开,如下所示:
fan_out
然后,您可以创建一个工厂方法或项目范围内的引用,在其中可以使用该代码段来实现您所要求的内容:
Regex re = new Regex(@"([a-zA-Z]+)(\d+)");
Match result = re.Match(input);
string alphaPart = result.Groups[1].Value;
string numberPart = result.Groups[2].Value;
当然,您应该实施更多的错误/空检查和更好的字符串比较,但这足以使您朝正确的方向前进。
答案 2 :(得分:0)
我通过创建此扩展方法解决了问题
public static DateTime test1(this DateTime d, string inputType)
{
if (inputType.Contains("DD"))
{
d = d.AddDays(Convert.ToInt32(inputType.Replace("DD", "")));
}
if (inputType.Contains("MM"))
{
d = d.AddMonths(Convert.ToInt32(inputType.Replace("MM", "")));
}
return d;
}