如何将月份名称(字符串)解析为整数以在 C# 中进行比较?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/258793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse a month name (string) to an integer for comparison in C#?
提问by spilliton
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?
我的谷歌搜索似乎表明唯一的方法是编写自己的方法,但这似乎是一个足够普遍的问题,我认为它已经在 .Net 中实现了,以前有人这样做过吗?
采纳答案by James Curran
DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month
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.
尽管就您的目的而言,您最好只创建一个Dictionary<string, int>
将月份名称映射到其值的映射。
回答by Adam Naylor
If you are using c# 3.0 (or above) you can use extenders
如果您使用的是 c# 3.0(或更高版本),您可以使用扩展程序
回答by Aaron Palmer
You could do something like this:
你可以这样做:
Convert.ToDate(month + " 01, 1900").Month
回答by Rune Grimstad
You can use the DateTime.Parse method to get a DateTime object and then check its Month property. Do something like this:
您可以使用 DateTime.Parse 方法获取 DateTime 对象,然后检查其 Month 属性。做这样的事情:
int month = DateTime.Parse("1." + monthName + " 2008").Month;
The trick is to build a valid date to create a DateTime object.
诀窍是建立一个有效的日期来创建一个 DateTime 对象。
回答by Treb
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.
不过,我不是 100% 确定 enum.Parse() 的语法。
回答by Rasmus Faber
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!
如果你使用了DateTime.ParseExact()
几个人推荐的-方法,你应该仔细考虑当应用程序在非英语环境中运行时你想要发生什么!
In Denmark, which of ParseExact("Januar", ...)
and ParseExact("January", ...)
should work and which should fail?
在丹麦,它的ParseExact("Januar", ...)
和ParseExact("January", ...)
应该工作,哪些应该失败?
That will be the difference between CultureInfo.CurrentCulture
and CultureInfo.InvariantCulture
.
这将是之间的差异CultureInfo.CurrentCulture
和CultureInfo.InvariantCulture
。
回答by Thabiso
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.
警告代码为 Beta 版。
回答by Ebenezer Ampiah
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:
我所做的是使用 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();
回答by Mark Seemann
You don't have to create a DateTime instance to do this. It's as simple as this:
您不必创建 DateTime 实例来执行此操作。就这么简单:
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:
我在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);
}
I'll leave it as an exercise to the reader to create an overload where you can pass in an explicit CultureInfo.
我将把它作为练习留给读者来创建一个重载,您可以在其中传递显式 CultureInfo。
回答by Maria Carolina Araujo
I translate it into C# code in Spanish version, regards:
我将其翻译成西班牙语版本的 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";
}
}