Tech Off Thread

28 posts

C# Sting converstion

Back to Forum: Tech Off
  • User profile image
    peoples

    Hi I know its a simple question, but I was wondering how to convert a int (date) to a string in c#. I have just started c# after using VB for some time.

     

    Gregor.

     

  • User profile image
    W3bbo

    An "int" date?

     

    If you've got a DateTime instance, just call myDate.ToString(); you can optionally specify a format-string or predefined culture settings to get the right format (e.g. myDate.ToString("yyyy-MM-dd"); or myDate.ToString(CultureInfo.CurrentCulture); )

     

    In .NET, every class inherits Object's .ToString() method, by default this method simply returns some basic information gained from Reflection, but some types (such as DateTime) override the behaviour. There is also the System.Convert class, but I find myself rarely using it (since it's nothing you can't do with the existing .TryParse / .Parse / .ToString methods.

  • User profile image
    figuerres

    W3bbo said:

    An "int" date?

     

    If you've got a DateTime instance, just call myDate.ToString(); you can optionally specify a format-string or predefined culture settings to get the right format (e.g. myDate.ToString("yyyy-MM-dd"); or myDate.ToString(CultureInfo.CurrentCulture); )

     

    In .NET, every class inherits Object's .ToString() method, by default this method simply returns some basic information gained from Reflection, but some types (such as DateTime) override the behaviour. There is also the System.Convert class, but I find myself rarely using it (since it's nothing you can't do with the existing .TryParse / .Parse / .ToString methods.

    Yeah I wonder if the OP meant:

     

    an International Date ?

    or possibly some long int format like 12252009 ?

     

  • User profile image
    W3bbo

    figuerres said:
    W3bbo said:
    *snip*

    Yeah I wonder if the OP meant:

     

    an International Date ?

    or possibly some long int format like 12252009 ?

     

    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) );

  • User profile image
    peoples

    W3bbo said:

    An "int" date?

     

    If you've got a DateTime instance, just call myDate.ToString(); you can optionally specify a format-string or predefined culture settings to get the right format (e.g. myDate.ToString("yyyy-MM-dd"); or myDate.ToString(CultureInfo.CurrentCulture); )

     

    In .NET, every class inherits Object's .ToString() method, by default this method simply returns some basic information gained from Reflection, but some types (such as DateTime) override the behaviour. There is also the System.Convert class, but I find myself rarely using it (since it's nothing you can't do with the existing .TryParse / .Parse / .ToString methods.

    I'm no good at this, this is my code.

    there is an error on the line, [string mydate..... ]and the next one ????????

     

    int thedate = this.dateTimePicker1.Value.Day & this.dateTimePicker1.Value.Month & this.dateTimePicker1.Value.Year;

    string mydate = thedate.ToString;

    this.richTextBox1.SaveFile(mydate);

  • User profile image
    peoples

    W3bbo said:

    An "int" date?

     

    If you've got a DateTime instance, just call myDate.ToString(); you can optionally specify a format-string or predefined culture settings to get the right format (e.g. myDate.ToString("yyyy-MM-dd"); or myDate.ToString(CultureInfo.CurrentCulture); )

     

    In .NET, every class inherits Object's .ToString() method, by default this method simply returns some basic information gained from Reflection, but some types (such as DateTime) override the behaviour. There is also the System.Convert class, but I find myself rarely using it (since it's nothing you can't do with the existing .TryParse / .Parse / .ToString methods.

    I got it you need () at the end of tostring !

     

    C# is new to me. Why does it not do the () in the dot completion system ?

     

    I got another question... In VB I use On Error Resume Next for errors, I need to write files and at times a file does not exist so i use the Error Handling to keep the code running. But I don't know how to do this in C# ???

     

    Thanks for help.

  • User profile image
    stevo_

    Dot notation is for member access.. the parenthesis denote method invocation.. without them it would be property/field access.

     

    The point being, ToString isn't a property of an object.. it is a method.. a method that says, give me a string representation of this object.

     

    (skipping your above code which I'm sure someone else will comment on).

  • User profile image
    TommyCarlier

    W3bbo said:
    figuerres said:
    *snip*

    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);

  • User profile image
    peoples

    TommyCarlier said:
    W3bbo said:
    *snip*

    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);

    Why can the first argument not be the day ?

  • User profile image
    stevo_

    peoples said:
    TommyCarlier said:
    *snip*

    Why can the first argument not be the day ?

    ... err because thats the way the constructor is defined? since the parameters aren't named, the order is very important.. how would the callee code know your intent when the intent is in your mind.

     

    http://msdn.microsoft.com/en-us/library/xcfzdy4x.aspx

     

    Also, you stated a few times that c# is confusing vs vb, but these concepts (parenthesis, dot notation and param order) are absolutely fundamentals of many languages, especially the most popular ones... (even vb which you claim to know well)

  • User profile image
    W3bbo

    peoples said:
    W3bbo said:
    *snip*

    I'm no good at this, this is my code.

    there is an error on the line, [string mydate..... ]and the next one ????????

     

    int thedate = this.dateTimePicker1.Value.Day & this.dateTimePicker1.Value.Month & this.dateTimePicker1.Value.Year;

    string mydate = thedate.ToString;

    this.richTextBox1.SaveFile(mydate);

    Your code won't work. In C# the '&' operator is bitwise AND, so your code is doing the bitwise AND of the integer representations of day, month, and year, which is meaningless.

     

    Just do this:

     

    DateTime myDate = myDateTimePicker.Value;

    String dateAsAString = myDate.ToString();

  • User profile image
    W3bbo

    TommyCarlier said:
    W3bbo said:
    *snip*

    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);

    Indeed, string conversion is hackish, but it has the benefit of being human-readable without needing to think too much about base-10 division.

     

    As for why I got the parameters wrong: I was getting it right in principle, I wasn't intending for my code to be taken verbatim (and if they did, it's a good exercise in why it's a good idea not to, so I can argue I got it wrong intentionally Big Smile ).

  • User profile image
    W3bbo

    peoples said:
    W3bbo said:
    *snip*

    I got it you need () at the end of tostring !

     

    C# is new to me. Why does it not do the () in the dot completion system ?

     

    I got another question... In VB I use On Error Resume Next for errors, I need to write files and at times a file does not exist so i use the Error Handling to keep the code running. But I don't know how to do this in C# ???

     

    Thanks for help.

    For error handling, you're meant to use Try/Catch and Exceptions; The "On Error Do Something" in VB.NET is meant as a crutch for backwards compatibility with VB6 (i.e. never use it in new projects).

     

    To see if a file exists or not:

     

    try {

        FileStream fs = new FileStream("path to file");

    } catch(FileNotFoundException fex) {

    }

     

    ...of course, you should never use exceptions for normal program flow, it's much better to test first:

     

    try {

        if( File.Exists("path to file") ) {

            // do file operation here

        } else {

            // show error message to user

        }

    } catch(IOException ex) {

    }

     

    And as you're using C#, you might as well make use of the using() {} block to ensure your program doesn't shít itself if something bad happens in the file IO ops.

  • User profile image
    peoples

    W3bbo said:
    peoples said:
    *snip*

    For error handling, you're meant to use Try/Catch and Exceptions; The "On Error Do Something" in VB.NET is meant as a crutch for backwards compatibility with VB6 (i.e. never use it in new projects).

     

    To see if a file exists or not:

     

    try {

        FileStream fs = new FileStream("path to file");

    } catch(FileNotFoundException fex) {

    }

     

    ...of course, you should never use exceptions for normal program flow, it's much better to test first:

     

    try {

        if( File.Exists("path to file") ) {

            // do file operation here

        } else {

            // show error message to user

        }

    } catch(IOException ex) {

    }

     

    And as you're using C#, you might as well make use of the using() {} block to ensure your program doesn't shít itself if something bad happens in the file IO ops.

    Thanks

  • User profile image
    peoples

    peoples said:
    W3bbo said:
    *snip*

    Thanks

    What does "master of baiters" mean Smiley

     

     

  • User profile image
    spivonious

    I think you'd benefit by a good book on C#.

     

    As for your code, the Value property of the DateTimePicker is already a DateTime type (similar to VB's Date type). Just call ToString() on the Value property and you'll get the default string representation of the date.

  • User profile image
    peoples

    spivonious said:

    I think you'd benefit by a good book on C#.

     

    As for your code, the Value property of the DateTimePicker is already a DateTime type (similar to VB's Date type). Just call ToString() on the Value property and you'll get the default string representation of the date.

    Can you recommend a good book for C# ?

  • User profile image
    peoples

    peoples said:
    spivonious said:
    *snip*

    Can you recommend a good book for C# ?

    Just one more question, I think if you call the datetime value you get a format like 11/12/2009, is it just a case of parseing out the "/" to make up the file name I want to use it as ?

     

    Thanks

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.