Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Amir Khan 1287 posts 2744 karma points
    Jan 21, 2014 @ 01:31
    Amir Khan
    0

    Split string without separators

    Hi, I'm trying to split a string without separators into individual parts. It needs to be a date, but none of the date time operators I've tried are working.

    Here's the string:20131105

    And the method I normally use:

    var birthDay = @currentMember.getProperty("birthday").Value;
    var birthDate = Convert.ToDateTime(birthDay);

    What am I missing here?

    
    
                    
  • Bjarne Fyrstenborg 1285 posts 4039 karma points MVP 8x c-trib
    Jan 21, 2014 @ 02:09
    Bjarne Fyrstenborg
    0

    Hi Amir

    I think it's because the string "20131105" isn't a valid format for the DateTime object.. I think you need to separate day, month, year with "-" or "." ortherwise it doesn't know which part is what..

    This works:

    string birthDay = "2013-11-05";
    var birthDate = DateTime.Parse(birthDay);
    <span>@birthDate.Day.ToString()</span>

    This doesn't work:

    string birthDay = "20131105";
    var birthDate = DateTime.Parse(birthDay);
    <span>@birthDate.Day.ToString()</span>

    /Bjarne

  • Amir Khan 1287 posts 2744 karma points
    Jan 21, 2014 @ 02:18
    Amir Khan
    0

    Hi Bjarne, how do you split a string without separators? I'm not creating the string so I don't have control over its initial format.

    -Amir

  • Bjarne Fyrstenborg 1285 posts 4039 karma points MVP 8x c-trib
    Jan 21, 2014 @ 02:37
    Bjarne Fyrstenborg
    101

    You could do something like this:

    string birthDay = "20131105";
    
    int year = int.Parse(birthDay.Substring(0, 4)); int month = int.Parse(birthDay.Substring(4, 2)); int day = int.Parse(birthDay.Substring(6, 2)); DateTime birthDate = new DateTime(year, month, day); <span>@birthDate.ToShortDateString()</span>

    or you could use other properties or methods of the DateTime object..

    you just have to know at which positions the year, month, day in located and .. that the string here only contains numbers and are exactly on 8 characters..

    e.g. if there only was 7 characters in the string, it would fails in the last Substring method for day as it can't take 2 more characters from position 6 if there only the 7 characters..

    /Bjarne

  • Amir Khan 1287 posts 2744 karma points
    Jan 21, 2014 @ 04:02
    Amir Khan
    0

    Bjarne, the format of the string is very consistent so this worked great. Thank you!

    -Amir

  • Mike Chambers 636 posts 1253 karma points c-trib
    Jan 21, 2014 @ 10:22
    Mike Chambers
    0

    You can always use parseExact...

    DateTime.ParseExact(birthDay, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

    [http://www.dotnetperls.com/datetime-parse]

Please Sign in or register to post replies

Write your reply to:

Draft