C#比较月份

时间:2013-07-26 07:36:28

标签: c# datetime

我正在尝试检查所选月份是否已经过去。

if (Convert.ToDateTime(DDMonths.SelectedItem.Text).Month > DateTime.Now.Month)
{
      //logic here if date is not in the past
}

DDMonths.SelectedItem.Text值为April

但是我收到以下格式异常错误:

  

字符串未被识别为有效的DateTime。

6 个答案:

答案 0 :(得分:5)

您可以使用以下命令按名称解析月份:

DateTime.ParseExact(DDMonths.SelectedItem.Text, "MMMM", CultureInfo.CurrentCulture ).Month

但是,如果可能的话,最好将Value中每个元素的DDMonths改为与月份对应的整数值。

答案 1 :(得分:2)

Convert.ToDateTime无法理解您的日期格式,您需要使用DateTime.ParseExact代替:

if(DateTime.ParseExact(DDMonths.SelectedItem.Text, "MMMM", CultureInfo.CurrentCulture).Month > DateTime.Now.Month) {
  ...
}

答案 2 :(得分:1)

这意味着你的行

 Convert.ToDateTime(DDMonths.SelectedItem.Text)

给你错误。你应该使用

DateTime.ParseExact(DDMonths.SelectedItem.Text,"MMMM",CultureInfo.InvariantCulture);

答案 3 :(得分:1)

因此,Text的{​​{1}}无法使用当前文化转换为DropDownList-Item。所以也许你正在显示月份名称(我假设)或错误是更多的减法。您可以使用DateTime以特定格式存储日期时间,例如:

ListItem.Value - > "yyyyMMdd"

然后你可以用这种方式解析它:

"20130726"

如果您想允许月份名称:

var dt = DateTime.ParseExact("20130726", "yyyyMMdd", CultureInfo.InvariantCulture);

答案 4 :(得分:1)

由于您只是在查找月份的数量,为什么要将其解析为DateTime?您可以直接从DateTimeFormatInfo获取它:

string input = "April";

var months = DateTimeFormatInfo.CurrentInfo.MonthNames;
var monthNumber = 1 + Array.FindIndex(months, x => x.Equals(input, StringComparison.CurrentCultureIgnoreCase));
if (monthNumber > DateTime.Now.Month)
{
    // ...
}

如果目前是4月,请考虑一下你想做什么。根据您的操作,您可能希望使用>=进行比较。

此外,如果您正在编写桌面应用程序,此代码(和其他代码)就可以了。但是,如果您正在编写Web应用程序并且此代码在服务器端运行,那么您还有两个问题:

  • 文化应与输入相匹配。您可能需要使用其他文化,或InvariantCulture
  • 您正在与DateTime.Now进行比较 - 这将位于服务器的时区。因此,如果世界其他地方的用户在新月份的第一天使用此服务器而服务器仍在前一天,则您的比较将失败。

答案 5 :(得分:0)

您应该使用ParseExact

DateTime变体
DateTime.ParseExact("April", "MMMM", CultureInfo.InvariantCulture).Month // outputs 4

您还应该尝试使用Value DDMonths.SelectedItem.Value )组件并根据需要填充

相关问题