Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Working with DateTime - 13

Download

Right click “Save as…”

Like strings, dates and times are represented using special types, and so deserve some attention. In this lesson we learn how to work with Date and Time data, how to create new instances of DateTime, how to add time, format the data for display, and more. Furthermore, we discuss the TimeSpan class...

Download source code for Working with DateTime

Tags:

Follow the Discussion

  • shivashiva

    Hi,
    I have a query as to when you created myValue object .
    1) If DateTime is a class and we are creating an object - I would have expected something similar to:
    DateTime myValue = new DateTime();
    then...
    myValue = myValue.Now() or something else...

    2) The second question is why is there no () after 'Now' - Is it not a method within the DateTime class?

  • CameronCameron

    Hey Shiva,

    1. You can instantiate DateTime three different ways. See the URL below regarding the DateTime struct for the different methods of doing such.

    2. Good catch! This is actually Now is a property within the DateTime struct. Now, I'm no expert so I'll let Mr. Tabor explain properties, which I'm pretty sure he will during this series. Keep watching to understand the difference between properties and methods.

    REFERENCE:
    http://msdn.microsoft.com/en-us/library/system.datetime.aspx

  • @Shiva ... regarding #1 ... GREAT CATCH.  The reason you don't have to create an instance of DateTime is that some of their methods and properties are marked as static, which means all instances of the class share the same implementation, and therefore no instance is required to use it.  It's been several months ... I can't recall whether I talk about static in this series (I *think* I do, but again, can't recall off the top of my head).  Search for "c# static" for more details.

     

    @Cameron ... thanks for the help.  Great explanations!

  • I had fun working with DateTime, I even created a console app that tells my grandfather happy birthday, how many days to wait until it tells him happy birthday, and even when his birthday pass, it will tell him to delete the file. This was a whole lot more fun and better then making a card or sending an eCard.

    Here is the code I used.

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
    
            static void Main(string[] args)
                
    
                /* If you want to use this file to tell someone happy birthday,
                 * all you must do is change the "OPEN THIS...", the birthDay value, 
                 * and the names, telling who's birthday it is and who it is from. 
                 */
    
            {
                // The Information at the top of the Console
                Console.WriteLine("O P E N   T H I S   P R O G R A M   2 0 1 2");
                Console.WriteLine("===========================================");
    
               
    
                //The Variables and Data Types
                DateTime rightNow = DateTime.Now.Date;
                DateTime birthDay = DateTime.Parse("01/28/2012");
                TimeSpan daysLeft = birthDay.Subtract(DateTime.Now);
    
                //If Today is his birthday
                if (rightNow == birthDay)
                {
    
                    Console.WriteLine("Happy Birthday Papa!\n \n From: name");
                    Console.WriteLine("======================================");
                    Console.ReadLine();
                }
                    // If his bithday has already passed
                else if (rightNow > birthDay)
                {
                    Console.WriteLine("Sorry, but this program is valid for this year only.  This program is no longer of  any use, you may delete it.");
                    Console.ReadLine();
                }
                    //If his birthday hasn't quite made it here yet
                else
                {
    
                    Console.WriteLine("Sorry, but you must wait " + daysLeft.Days + " days, then open this file. \n");
                    Console.WriteLine("It is currently: " + DateTime.Now);
                    Console.ReadLine();
                }
            }
        }
    }
    

  • @animedragonfighter:Cool idea!  Thanks for posting this!

  • ThorvaldThorvald

    Hi, may you please explain the .TryParse method (or what it is)?
    P.S. Please excuse my bad English(I'am from Norway).

  • @Thorvald:  Hi Thorvald!  Let me start here:

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

    This is for the DOUBLE data type, but just about every data type has a similar TryParse method.

    Let's look at a portion of the example on that web page:

     

    string value;
    
    double number;
    
    value = Double.MinValue.ToString();
    
    if (Double.TryParse(value, out number))
    
       Console.WriteLine(number);
    
    else
    
    .
    
    .
    
    .

     

    In line 7 line (the 'if' statement) the example uses the TryParse method to accept a string.  In line 5, WE KNOW the variable called 'value' should convert back to a double data type because we're merely taking the absolute minimum value (using the MinValue property of the double data type) of a double and converting it to a string.  TryParse looks at 'value' and asks "Can I work with this?"  If yes, it will do two things all at once ... (1) it will return the value 'True', and (2) it will actually perform the conversion and stick the converted "value" into the 'out' parameter, the second parameter, we sent into the TryParse method.  That 'out' parameter means that we can return values FROM a method using parameters (as you know, the usual way is just to use the 'return' keyword inside the body of the method).  Since TryParse returns a boolean (true or false), we can use it to ATTEMPT to parse first, if the parse works, do it, if not then in the else condition of the if statement we can try something else (ask the user for a new value, find the new value somewhere else, break out of a loop, whatever).

    The key ideas here is that TryParse wears two hats, returning a "status" via the return value (true or false) and if true, it will also return the converted number in the 'out' parameter.

    Does that clear it up?  Please let me know if I can help further!  Best wishes,

    Bob

  • MicchelMicchel

    i want to know ... how can we get a date from user ... ?
    can i do it using Console.ReadLine(date);
    where date is a datatype of string which i have described earlier ?
    i am really confused ... help me with itttt asapppp

  • @Micchel: You will use ReadLine to retrieve a value form the user which will return a string.  Then, you will use DateTime.TryParse to (1) attempt to parse that string into a DateTime object, and (2) actually do it if it can, and (3) return a boolean 'false' value if it can't ... see this entry in Microsoft's help:

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

  • IlyaIlya

    In first example why do we need " Console.WriteLine(myValue.ToString());
    if it works: Console.WriteLine(myValue);

  • @Ilya: Hi, good question.  The answer is: you don't need to do this.  I am merely being over cautious.  In my mind, Console.WriteLine() accepts strings and prints strings to the Console.  That is half true -- it prints strings to the Console, however it will accept many different data types.  The WriteLine() method is overloaded, meaning it has many different implementations allowing it to accept many different data types.  Good catch.

  • WilsonWilson

    Hi Bob, I have the following error when using DateTime in my code, can you point me the right direction? Thanks.

    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
    DateTime DOB = dateTimePicker1.Value;
    int sexagenaryYear = EastAsianLunisolarCalendar.GetSexagenaryYear(DOB);
    }

    Error: An object reference is required for the non-static field, method, or property 'System.Globalization.EastAsianLunisolarCalendar.GetSexangenaryYear(DOB)'

  • BruceBruce

    Wilson,

    I'm just learning myself so I really don't know, and could be way off, but I don't see (in intellisense) a GetSexangenaryYear method in that class.

  • BruceBruce

    Actually Wilson, I see that if you declare a variable of Type EastAsianLunisolarCalendar you can get that method to show up from the declared variable, (I suspect it only shows up after a variable of that type is declared because the method isn't static, but again, I'm just learning so maybe not) I believe your instance of a calander of this type must also first be populated with data of that calander type (I'm not familiar with it and don't know what would be valid data for that data type) before you can use that method if its not a static method, but again I caution you, I really don't know what I'm talking about, I'm just trying to learn myself, but that's my best guess. EastAsianLunisolarCalendar is not an actual instance of a calander object that exists so you can use it, but rather a definition of a specific type of calander that must be declared or "instanciated" as a variable and have data, or possibly a reference to data, of this type assigned to your variable before you can use that method. I expermented a little, but wasn't familiar with that type of calander, so I didn't know what values to assign to my instance of a variable that type.
    When I tried;
    string s = "12/15/2001";
    DateTime mydate = DateTime.Parse(s);
    Console.WriteLine(mydate.ToString());
    Console.ReadLine();
    EastAsianLunisolarCalendar a;
    int b = a.GetSexagenaryYear(mydate) ;
    Console.WriteLine(b.ToString());
    Console.ReadLine();

    The only error I got was "Use of unassigned local variable 'a'" I couldn't figure out how to assign valid data of type EastAsianLunisolarCalendar to my variable called "a". I hope that anything I said helps. I normally wouldn't even comment about something I know so little about, but I see Bob hasn't responded to you in 6 days, so I tried to figure it out myself and possibly learn a little something in the process. Good Luck.

Remove this comment

Remove this thread

close

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.