如何将月份名称转换为int?

时间:2010-08-05 01:47:16

标签: string datetime .net-3.5

我在存储过程中有一个名为Month的列,它以字符串名称术语(例如,1月,2月,3月等)返回给我。

我想将其转换为整数。

如果不使用多个精选案例陈述,是否可以这样做?

我想在.NET 3.5中执行此操作

4 个答案:

答案 0 :(得分:2)

您可以使用DateTime.Parse,然后获取日期的Month属性:

string monthName = "January";
DateTime.Parse(String.Format("{0} 1, 2000", monthName)).Month

答案 1 :(得分:0)

在SQL Server中执行此操作SELECT DATEPART(month, GETDATE())

此问题的副本How to parse a month name (string) to an integer for comparison in C#?

答案 2 :(得分:0)

我最近遇到过这个问题(在客户端使用Javascript),经过互联网上的一些搜索,我决定自己做。虽然我是用Javascript做的,但我还是会给你一个.net解决方案。 首先是Javascript:

function convertToIntMonth(monText) {
//Your arrays for the valid months for which you can throw exception (I did not do it) if the parameter is out of these 12.
        var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        var monInt;
        for (i = 0; i < 12; i++) {
//in this loop, we'll check for the match in parameter and array items.
            if (monText == monthNames[i])
            { 
//If match is found, we'll return the +1 value of actual match (as month array's index goes from 0 to 11, and we require it from 1 to 12)
monInt=i+1}
        }
        return monInt;
    }

现在的.NET(C#):还没有测试过,我希望你能找到逻辑

public int convertToIntMonth(string monText) {
        string[] monthNames = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        string monInt=0;
        for (int i = 0; i < 12; i++) {
            if (monText == monthNames[i])
            { monInt=i+1}
        }
        return monInt;
    }

答案 3 :(得分:-1)

你可以在一个数组中存储Name-&gt;数字映射(查看数组,直到找到你想要的那个)或一个哈希(在哈希中查找月份名称以获得一个数字 - 从支持任何数字中获益语言和缩写也是如此)。我宁愿将信息存储在数据结构中而不是代码中,但这可能只是我自己的非理性行为。

修改

为了回应@ roboshop的“听起来像很多工作”,或许它与平台支持的单行进行比较,但如果您的客户要求您支持缩写,例如“Jan”,“Fe”,“ Mar“,我认为使用数据结构可以提供更多的灵活性:

months = { "ja" => 1, "jan" => 1, "january" => 1,
           "fe" => 2, "feb" => 2, "february" => 2,
           "ma" => 3, "mar" => 3, "march" => 3,
           "ap" => 4, "apr" => 4, "april" => 4,
           "my" => 5, "may" => 5,
           "jn" => 6, "jun" => 6, "june" => 6,
           "jl" => 7, "jul" => 7, "july" => 7,
           "au" => 8, "aug" => 8, "august" => 8,
           "se" => 9, "sep" => 9, "sept" => 9, "september" => 9,
           "oc" => 10, "oct" => 10, "october" => 10,
           "no" => 11, "nov" => 11, "november" => 11,
           "de" => 12, "dec" => 12, "december" => 12,
           "januar" => 1,
           "februar" => 2,
           "märz" => 3,
           "mai" => 5,
           "juni" => 6,
           "oktober" => 10,
           "dezember" => 12}

puts "Month %s is %d" % [ARGV[0], months[ARGV[0].downcase]]

当然,现在您必须知道用户想要的月份的本地化版本,但支持请求的缩写要容易得多。