Aan
Aan

Reputation: 12890

Getting part of a string

I have somthing similar to:

 String^  s2="22/12/2012";

How I can get the year part in another String ? The year part of the previous dummy example is 2012.

I am fine with C# if you can give answer, this is the corresponding code:

string  s2="22/12/2012";

Upvotes: 0

Views: 102

Answers (3)

andy
andy

Reputation: 6079

var result = DateTime.Parse(s2, new CultureInfo("en-US")).Year;

Change the culture info if required

OR

string[] date = s2.Split('/');

 if (date.Length == 3)
 {
    //date[2]
 }

Upvotes: 1

Priyank Patel
Priyank Patel

Reputation: 6996

string [] split = Regex.Split(s2, @"/");
string year = split[2];

Upvotes: 2

Blachshma
Blachshma

Reputation: 17395

Is this what you want?

string theYear = DateTime.Parse(s2).Year.ToString();

Of course you should check that it is a valid string like this:

            DateTime theDate;
            string theYear;
            if (DateTime.TryParse(s2, out theDate))
            {
                theYear = theDate.Year.ToString();
            }

Upvotes: 1

Related Questions