Tech Off Post

Single Post Permalink

View Thread: C# Sting converstion
  • User profile image

    W3bbo said:
    figuerres said:

    If its a date or time value stored in an integer representation of something like ticks or miliseconds then it's trivial, just multiply and cast to long to get ticks, then use DateTime's ticks constructor.


    If it's something like 25122009 then the OP has my sympathy, how does something like that happen?


    Well, if it is like 25122009 then convert it to a digit array (might as well just convert to a string) then extract the bits you need, then convert to int or datetime:


    String input = 25122009.ToString();

    String dayStr = input.Substring(0,2);

    String monStr = input.Substring(2,2);

    String yerStr = input.Substring(4,4);


    DateTime date = new DateTime( int.Parse( dayStr ), int.Parse(monStr), int.Parse(yerStr) );

    Converting to string, substringing and parsing to integers is not really nice. And the DateTime-constructor you use is used wrongly: the first argument is the year and not the day.

    Long live integer division and modulo:

    int d = 25122009;
    DateTime date =
      new DateTime(
        d / 1000000,
        (d / 10000) % 100,
        d % 10000);