0

I have this parameter below

token[10] ="Date: UTC 2012-02-02 17:09:04"

i wrote the following code to extract only year and month,so it suppose to be "201202". is this anyway i can get only those value with out using split,i know we can use regex too but is this any other way to extract those values

        string Encdate = tokens[10];
        string[] EncdateValue = Encdate.ToString().Split(' ');
        string Encdatesplit = EncdateValue[2].TrimStart();
        string[] YYMM = Encdatesplit.ToString().Split('-');
        string YYMMVal = YYMM[0] + YYMM[1];
6
  • Could do a little string manipulation, cast it to a datetime, and then do a formatted .ToString() on it Commented Feb 21, 2012 at 0:21
  • Why don't you parse the date into a DateTime object and extract the components using the DateTime functions. Get the year and month and concatenate them to get your desired value. Commented Feb 21, 2012 at 0:23
  • @agarcian,that sounds great though. Commented Feb 21, 2012 at 0:26
  • @StefanH,thanks a lot, i will try follow your idea. Commented Feb 21, 2012 at 0:27
  • 1
    Seems that your data is at a fixed position, so why bother with Split() or Date conversion, do a simple Substring() extraction as @keijzers suggest (after replacing token with Encdate) Commented Feb 21, 2012 at 0:34

2 Answers 2

4

Just use DateTime.ParseExact method and access the Year and Month properties from the returned DateTime object, otherwise use Date/Time string formatters and the DateTime.ToString(string) method to get the yyyyMM format, here is an example:

        var d = DateTime.ParseExact(token, "'Date: UTC' yyyy-MM-dd HH:mm:ss", 
                CultureInfo.InvariantCulture, 
                DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal);

        Console.WriteLine(d.ToString("yyyyMM"));
Sign up to request clarification or add additional context in comments.

Comments

0

var t = token[10];

You also could use a concatenation of the needed characters:

string Encdate = t[10] + t[11] + t[12] + t[13] + t[15] + t[16];

Or use substring (for adding the two):

string Encdate = t.Substring(10, 4) + t.Substring(15, 2);

Or a substring and a remove:

string Encdate = t.Substring(10, 7).Remove(4);

3 Comments

my token[10] value is "Date: UTC 2012-02-02 17:09:04".
In your question is stated: token ="Date: UTC 2012-02-02 17:09:04"
You are welcome ... however are my answers not what you are looking for? they all result in "201202".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.