如何在 C# 中将月份名称(字符串)解析为整数以进行比较?

发布于 2024-07-08 11:17:16 字数 201 浏览 6 评论 0原文

我需要能够比较数组中的一些月份名称。

如果有一些直接的方法就好了,比如:

Month.toInt("January") > Month.toInt("May")

我的谷歌搜索似乎表明唯一的方法是编写你自己的方法,但这似乎是一个足够常见的问题,我认为它已经在.Net中实现了,以前有人这样做过吗?

I need to be able to compare some month names I have in an array.

It would be nice if there were some direct way like:

Month.toInt("January") > Month.toInt("May")

My Google searching seems to suggest the only way is to write your own method, but this seems like a common enough problem that I would think it would have been already implemented in .Net, anyone done this before?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

故事与诗 2024-07-15 11:17:16

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

不过,出于您的目的,您最好只创建一个 DictionaryDictionarycode> 将月份名称映射到其值。

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int> mapping the month's name to its value.

马蹄踏│碎落叶 2024-07-15 11:17:16

你可以这样做:

Convert.ToDate(month + " 01, 1900").Month

You could do something like this:

Convert.ToDate(month + " 01, 1900").Month
往昔成烟 2024-07-15 11:17:16

如果您使用几个人建议的 DateTime.ParseExact() 方法,您应该仔细考虑当应用程序在非英语环境中运行时您希望发生什么!

在丹麦,ParseExact("Januar", ...)ParseExact("January", ...) 哪个应该有效,哪个应该失败?

这就是 CultureInfo.CurrentCultureCultureInfo.InvariantCulture 之间的区别。

If you use the DateTime.ParseExact()-method that several people have suggested, you should carefully consider what you want to happen when the application runs in a non-English environment!

In Denmark, which of ParseExact("Januar", ...) and ParseExact("January", ...) should work and which should fail?

That will be the difference between CultureInfo.CurrentCulture and CultureInfo.InvariantCulture.

清风挽心 2024-07-15 11:17:16

一个简单的解决方案是创建一个包含名称和值的字典。 然后使用 Contains() 您可以找到正确的值。

Dictionary<string, string> months = new Dictionary<string, string>()
{
                { "january", "01"},
                { "february", "02"},
                { "march", "03"},
                { "april", "04"},
                { "may", "05"},
                { "june", "06"},
                { "july", "07"},
                { "august", "08"},
                { "september", "09"},
                { "october", "10"},
                { "november", "11"},
                { "december", "12"},
};
foreach (var month in months)
{
    if (StringThatContainsMonth.ToLower().Contains(month.Key))
    {
        string thisMonth = month.Value;
    }
}

One simply solution would be create a Dictionary with names and values. Then using Contains() you can find the right value.

Dictionary<string, string> months = new Dictionary<string, string>()
{
                { "january", "01"},
                { "february", "02"},
                { "march", "03"},
                { "april", "04"},
                { "may", "05"},
                { "june", "06"},
                { "july", "07"},
                { "august", "08"},
                { "september", "09"},
                { "october", "10"},
                { "november", "11"},
                { "december", "12"},
};
foreach (var month in months)
{
    if (StringThatContainsMonth.ToLower().Contains(month.Key))
    {
        string thisMonth = month.Value;
    }
}
送君千里 2024-07-15 11:17:16

您可以使用 DateTime.Parse 方法获取 DateTime 对象,然后检查其 Month 属性。 做这样的事情:

int month = DateTime.Parse("1." + monthName + " 2008").Month;

技巧是构建一个有效的日期来创建一个 DateTime 对象。

You can use the DateTime.Parse method to get a DateTime object and then check its Month property. Do something like this:

int month = DateTime.Parse("1." + monthName + " 2008").Month;

The trick is to build a valid date to create a DateTime object.

°如果伤别离去 2024-07-15 11:17:16

您可以使用月份的枚举:

public enum Month
{
    January,
    February,
    // (...)
    December,
}    

public Month ToInt(Month Input)
{
    return (int)Enum.Parse(typeof(Month), Input, true));
}

不过,我对 enum.Parse() 的语法不是 100% 确定。

You can use an enum of months:

public enum Month
{
    January,
    February,
    // (...)
    December,
}    

public Month ToInt(Month Input)
{
    return (int)Enum.Parse(typeof(Month), Input, true));
}

I am not 100% certain on the syntax for enum.Parse(), though.

幸福丶如此 2024-07-15 11:17:16

您不必创建 DateTime 实例来执行此操作。 就这么简单:

public static class Month
{
    public static int ToInt(this string month)
    {
        return Array.IndexOf(
            CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
            month.ToLower(CultureInfo.CurrentCulture))
            + 1;
    }
}

我正在 da-DK 文化上运行,所以这个单元测试通过了:

[Theory]
[InlineData("Januar", 1)]
[InlineData("Februar", 2)]
[InlineData("Marts", 3)]
[InlineData("April", 4)]
[InlineData("Maj", 5)]
[InlineData("Juni", 6)]
[InlineData("Juli", 7)]
[InlineData("August", 8)]
[InlineData("September", 9)]
[InlineData("Oktober", 10)]
[InlineData("November", 11)]
[InlineData("December", 12)]
public void Test(string monthName, int expected)
{
    var actual = monthName.ToInt();
    Assert.Equal(expected, actual);
}

我将把它作为练习留给读者,以创建一个可以传入的重载明确的文化信息。

You don't have to create a DateTime instance to do this. It's as simple as this:

public static class Month
{
    public static int ToInt(this string month)
    {
        return Array.IndexOf(
            CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
            month.ToLower(CultureInfo.CurrentCulture))
            + 1;
    }
}

I'm running on the da-DK culture, so this unit test passes:

[Theory]
[InlineData("Januar", 1)]
[InlineData("Februar", 2)]
[InlineData("Marts", 3)]
[InlineData("April", 4)]
[InlineData("Maj", 5)]
[InlineData("Juni", 6)]
[InlineData("Juli", 7)]
[InlineData("August", 8)]
[InlineData("September", 9)]
[InlineData("Oktober", 10)]
[InlineData("November", 11)]
[InlineData("December", 12)]
public void Test(string monthName, int expected)
{
    var actual = monthName.ToInt();
    Assert.Equal(expected, actual);
}

I'll leave it as an exercise to the reader to create an overload where you can pass in an explicit CultureInfo.

×纯※雪 2024-07-15 11:17:16
Public Function returnMonthNumber(ByVal monthName As String) As Integer
    Select Case monthName.ToLower
        Case Is = "january"
            Return 1
        Case Is = "february"
            Return 2
        Case Is = "march"
            Return 3
        Case Is = "april"
            Return 4
        Case Is = "may"
            Return 5
        Case Is = "june"
            Return 6
        Case Is = "july"
            Return 7
        Case Is = "august"
            Return 8
        Case Is = "september"
            Return 9
        Case Is = "october"
            Return 10
        Case Is = "november"
            Return 11
        Case Is = "december"
            Return 12
        Case Else
            Return 0
    End Select
End Function

警告代码为 Beta 版本。

Public Function returnMonthNumber(ByVal monthName As String) As Integer
    Select Case monthName.ToLower
        Case Is = "january"
            Return 1
        Case Is = "february"
            Return 2
        Case Is = "march"
            Return 3
        Case Is = "april"
            Return 4
        Case Is = "may"
            Return 5
        Case Is = "june"
            Return 6
        Case Is = "july"
            Return 7
        Case Is = "august"
            Return 8
        Case Is = "september"
            Return 9
        Case Is = "october"
            Return 10
        Case Is = "november"
            Return 11
        Case Is = "december"
            Return 12
        Case Else
            Return 0
    End Select
End Function

caution code is in Beta version.

合久必婚 2024-07-15 11:17:16

在问题提出七年后回答这个问题,可以使用内置方法进行比较:

Month.toInt("January") > Month.toInt("May")

为简单起见

Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                 t => t.Equals("January", StringComparison.CurrentCultureIgnoreCase)) >
Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                 t => t.Equals("May", StringComparison.CurrentCultureIgnoreCase))

,可以将其重构为扩展方法。 以下是 LINQPad 示例(因此调用 Dump() 方法):

void Main()
{
    ("January".GetMonthIndex() > "May".GetMonthIndex()).Dump();
    ("January".GetMonthIndex() == "january".GetMonthIndex()).Dump();
    ("January".GetMonthIndex() < "May".GetMonthIndex()).Dump();
}

public static class Extension {
    public static int GetMonthIndex(this string month) {
        return Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                         t => t.Equals(month, StringComparison.CurrentCultureIgnoreCase));
    }
}

输出:

False
True
True

And answering this seven years after the question was asked, it is possible to do this comparison using built-in methods:

Month.toInt("January") > Month.toInt("May")

becomes

Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                 t => t.Equals("January", StringComparison.CurrentCultureIgnoreCase)) >
Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                 t => t.Equals("May", StringComparison.CurrentCultureIgnoreCase))

Which can be refactored into an extension method for simplicity. The following is a LINQPad example (hence the Dump() method calls):

void Main()
{
    ("January".GetMonthIndex() > "May".GetMonthIndex()).Dump();
    ("January".GetMonthIndex() == "january".GetMonthIndex()).Dump();
    ("January".GetMonthIndex() < "May".GetMonthIndex()).Dump();
}

public static class Extension {
    public static int GetMonthIndex(this string month) {
        return Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,
                         t => t.Equals(month, StringComparison.CurrentCultureIgnoreCase));
    }
}

With output:

False
True
True
逆光下的微笑 2024-07-15 11:17:16

如果您使用的是 c# 3.0(或更高版本),您可以使用扩展器

If you are using c# 3.0 (or above) you can use extenders

扮仙女 2024-07-15 11:17:16

我将其翻译成西班牙语版本的 C# 代码,问候:

public string ObtenerNumeroMes(string NombreMes){

       string NumeroMes;   

       switch(NombreMes) {

        case ("ENERO") :
            NumeroMes = "01";
            return NumeroMes;

        case ("FEBRERO") :
            NumeroMes = "02";
            return NumeroMes;

        case ("MARZO") :
            NumeroMes = "03";
            return NumeroMes;

        case ("ABRIL") :
            NumeroMes = "04";
            return NumeroMes;

        case ("MAYO") :
            NumeroMes = "05";
            return NumeroMes;

        case ("JUNIO") :
            NumeroMes = "06";
            return NumeroMes;

        case ("JULIO") :
            NumeroMes = "07";
            return NumeroMes;

        case ("AGOSTO") :
            NumeroMes = "08";
            return NumeroMes;

        case ("SEPTIEMBRE") :
            NumeroMes = "09";
            return NumeroMes;

        case ("OCTUBRE") :
            NumeroMes = "10";
            return NumeroMes;

        case ("NOVIEMBRE") :
            NumeroMes = "11";
            return NumeroMes;

        case ("DICIEMBRE") :
            NumeroMes = "12";
            return NumeroMes;

            default:
            Console.WriteLine("Error");
            return "ERROR";

        }

   }

I translate it into C# code in Spanish version, regards:

public string ObtenerNumeroMes(string NombreMes){

       string NumeroMes;   

       switch(NombreMes) {

        case ("ENERO") :
            NumeroMes = "01";
            return NumeroMes;

        case ("FEBRERO") :
            NumeroMes = "02";
            return NumeroMes;

        case ("MARZO") :
            NumeroMes = "03";
            return NumeroMes;

        case ("ABRIL") :
            NumeroMes = "04";
            return NumeroMes;

        case ("MAYO") :
            NumeroMes = "05";
            return NumeroMes;

        case ("JUNIO") :
            NumeroMes = "06";
            return NumeroMes;

        case ("JULIO") :
            NumeroMes = "07";
            return NumeroMes;

        case ("AGOSTO") :
            NumeroMes = "08";
            return NumeroMes;

        case ("SEPTIEMBRE") :
            NumeroMes = "09";
            return NumeroMes;

        case ("OCTUBRE") :
            NumeroMes = "10";
            return NumeroMes;

        case ("NOVIEMBRE") :
            NumeroMes = "11";
            return NumeroMes;

        case ("DICIEMBRE") :
            NumeroMes = "12";
            return NumeroMes;

            default:
            Console.WriteLine("Error");
            return "ERROR";

        }

   }
£噩梦荏苒 2024-07-15 11:17:16

我所做的是使用 SimpleDateFormat 创建一个格式字符串,并将文本解析为日期,然后从中检索月份。 代码如下:

int year = 2012 \\or any other year
String monthName = "January" \\or any other month
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
int monthNumber = format.parse("01-" + monthName + "-" + year).getMonth();

What I did was to use SimpleDateFormat to create a format string, and parse the text to a date, and then retrieve the month from that. The code is below:

int year = 2012 \\or any other year
String monthName = "January" \\or any other month
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
int monthNumber = format.parse("01-" + monthName + "-" + year).getMonth();
心头的小情儿 2024-07-15 11:17:16
int selectedValue = 0;
            switch (curentMonth)
            {
                case "January":
                    selectedValue = 1;
                    break;
                case "February":
                    selectedValue = 2;
                    break;
            }
            if (selectedValue != 0)
            {
               /* var list= db.model_name.Where(x => x.column== selectedValue);
                return list; */
            }
            return Ok(selectedValue);
int selectedValue = 0;
            switch (curentMonth)
            {
                case "January":
                    selectedValue = 1;
                    break;
                case "February":
                    selectedValue = 2;
                    break;
            }
            if (selectedValue != 0)
            {
               /* var list= db.model_name.Where(x => x.column== selectedValue);
                return list; */
            }
            return Ok(selectedValue);
温柔女人霸气范 2024-07-15 11:17:16

此代码适用于 awk,但很容易适应 C/C++/C#

awk 中,所有索引都是 ” 1-based" 而不是 "0-based" - 参考字符串的前缘 "=" 只是预移动位置。 对于任何基于 0 的语言,删除该 "="`

function __(_) {  #  input - Eng. month names, any casing, min. 3 letters
                  # output - MM : [01-12], zero-padded
    return \
    ((_=toupper(_)) ~ "^[OND]" ? "" : _<_) \
    (index("=ANEBARPRAYUNULUGEPCTOVEC", substr(_ "",_+=_^=_<_,_))/_)
}

参考字符串一开始可能看起来很奇怪 -

月份名称的第2+3个字母构成唯一的集合

因此OP可以输入月份的英文名称,完整的或缩写的,它会返回一个零填充的2位月份数字。 如果您需要它是整数形式,那么只需擦掉执行填充的中间行即可。

您会注意到仅声明了 1 个输入变量,并且没有任何其他临时变量 - awk 的主要优势之一是其极端敏捷性涉及变量的动态类型,
即使对于真正不合逻辑的操作,例如取 string 变量的 "0th-power"

<前><代码>“波士顿”^ 0

这会无缝地将该变量强制转换为数字数据类型,新值为1

这种灵活性使得在不再需要原始输入值时可以出于任何其他目的回收和重新使用输入临时变量。

This code is for awk, but easily adaptable to C/C++/C#

in awk, all indices are "1-based" instead of "0-based" - the leading edge "=" of the reference string is simply pre-shifting the positions. remove that "=" for any 0-based languages`

function __(_) {  #  input - Eng. month names, any casing, min. 3 letters
                  # output - MM : [01-12], zero-padded
    return \
    ((_=toupper(_)) ~ "^[OND]" ? "" : _<_) \
    (index("=ANEBARPRAYUNULUGEPCTOVEC", substr(_ "",_+=_^=_<_,_))/_)
}

The reference string might look odd at first -

the 2nd + 3rd letters of month names constitute a unique set

So OP can input the english name of the months, full or abbreviated, and it'll return a zero-padded 2-digit month number. If you need it to be in integer form, then just scrub out the middle line that performs the padding.

You'll notice only 1 input variable declared and no other temp variables whatsoever - one of awk's major strengths is its extreme agility when it comes to dynamic typing of variables,
even for truly illogical operations like taking the "0th-power" of a string variable like

"Boston" ^ 0 

This would seamlessly coerce that variable to a numeric data type, with a new value of 1.

This flexibility enables the recycling and re-using of the input temp variable(s) for any other purpose the moment the original input value(s) is/are no longer needed.

没企图 2024-07-15 11:17:16

这段代码可以帮助您...

using System.Globalization;

....

string FullMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.UtcNow.Month);

GetMonthName 方法 - 它返回字符串...

如果您想获取整数月份,那么只需使用 -

DateTime dt= DateTime.UtcNow;
int month= dt.Month;

我希望,它可以帮助您!

谢谢!!!

This code helps you...

using System.Globalization;

....

string FullMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.UtcNow.Month);

GetMonthName Method - it returns string...

If you want to get a month as an integer, then simply use -

DateTime dt= DateTime.UtcNow;
int month= dt.Month;

I hope, it helps you!!!

Thanks!!!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文