C# 解析日期字符串以获取年份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9246466/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:31:53  来源:igfitidea点击:

Parsing a date string to get the year

c#date

提问by user1204195

I have a string variable that stores a date like "05/11/2010".

我有一个存储日期的字符串变量,如“05/11/2010”。

How can I parse the string to get only the year?

如何解析字符串以仅获取年份?

So I will have another year variable like year = 2010.

所以我将有另一个年份变量,如year = 2010.

回答by dtb

You can use the DateTime.Parse Methodto parse the string to a DateTimevalue which has a Year Property:

您可以使用DateTime.Parse 方法将字符串解析为具有Year 属性DateTime值:

var result = DateTime.Parse("05/11/2010").Year;
// result == 2010

Depending on the culture settings of the operating system, you may need to provide a CultureInfo:

根据操作系统的文化设置,您可能需要提供CultureInfo

var result = DateTime.Parse("05/11/2010", new CultureInfo("en-US")).Year;
// result == 2010

回答by Josh Mein

This should work for you.

这应该对你有用。

string myDate = "05/11/2010"; 
DateTime date = Convert.ToDateTime(myDate);
int year = date.Year;

回答by Sergey Brunov

If the date string format is fixed (dd/MM/yyyy), I would like to recommend you using DateTime.ParseExact Method.

如果日期字符串格式是固定的(dd/MM/yyyy),我建议您使用DateTime.ParseExact Method

The code:

编码:

const string dateString = "12/02/2012";
CultureInfo provider = CultureInfo.InvariantCulture;
// Use the invariant culture for the provider parameter,
// because of custom format pattern.
DateTime dateTime = DateTime.ParseExact(dateString, "dd/MM/yyyy", provider);
Console.WriteLine(dateTime);

Also I think it might be a little bit faster than DateTime.Parse Method, because the Parse method tries parsing several representations of date-time string.

另外我认为它可能比DateTime.Parse Method快一点,因为 Parse 方法尝试解析日期时间字符串的几种表示形式。

回答by Ramgy Borja

you could also used Regexto get the yearin the string "05/11/2010"

您还可以使用Regex在字符串“05/11/2010”中获取年份

public string getYear(string str)
{
    return (string)Regex.Match(str, @"\d{4}").Value;
}

var result = getYear("05/11/2010");

2010

回答by John Pittaway

Variant of dtb that I use:

我使用的 dtb 变体:

string Year = DateTime.Parse(DateTime.Now.ToString()).Year.ToString();