Thursday, 19 April 2018

How to Build a Decision Tree for Classification - (Step by Step Procedure Using Entropy and Gain)

In this Lesson, I would teach you how to build a decision tree step by step in very easy way, with clear explanations and diagrams.

Content
  1. What are Decision Trees
  2. Exercise for this Lesson
  3. The ID3 Algorithm for Building Decision Trees
  4. Step by Step Procedure
  5. Final Notes

1. What are Decision Trees


A decision tree is a tree-like strucure that is used as a model for classifying data. A decision tree decomposes the data into subtrees made of other sub-trees and/or leaf nodes.
A decision tree is made up of three types of nodes
Decision Nodes: These type of node have two or more branches
Leaf Nodes: The lowest nodes which represents decision
Root Node: This is also a decision node but at the topmost level

The question is : How to we build a decision tree? Let's see!

2. Exercise for this Lesson


Consider the table below. It represent factors that affect whether John would go out to play golf or not. Using the data in the table, build a a decision tree to model that can be used to predict if John would play golf or not.

Figure 1: Exercise on Decision Trees


3. Algorithm for Building Decision Trees - The ID3 Algorithm(you can skip this!)


This is the algorithm you need to learn, that is applied in creating a decision tree. Although you don't need to memorize it but just know it. It is called the ID3 algorithm by J. R. Quinlan. The algorithm uses Entropy and Informaiton Gain to build the tree.
 Let:

S = Learning Set
A = Attibute Set
V = Attribute Values


Begin
Load learning sets  and create decision tree root node(rootNode), add learning set S into root not as its subset
For rootNode, compute Entropy(rootNode.subset) first
If Entropy(rootNode.subset) == 0 (subset is homogenious)
      return a leaf node

If Entropy(rootNode.subset)!= 0 (subset is not homogenious)
     compute Information Gain for each attribute left (not been used for spliting)
     Find attibute A with Maximum(Gain(S, A))
     Create child nodes for this root node and add to rootNode in the decision tree

For each child of the rootNode
   Apply ID3(S, A, V)
   Continue until a node with Entropy of 0 or a leaf node is reached
End

(You actually don't have to worry trying to understand every bit of this algorithm. The application would make is very clear)



4. Step by Step Procedure for Building a Decision Tree


Here I would give you a simple step by step procedure that is super-easy to follow in creating a decision tree no matter how complex it could be.
Start by determining the root of the tree and the class column

Step 1: Determine the Decision Column



Since decision trees are used for clasification, you need to determine the classes which are the basis for the decision.
In this case, it it the last column, that is Play Golf column with classes Yes and No.

To determine the rootNode we need to compute the entropy.
To do this, we create a frequency table for the classes (the Yes/No column).

Table 2: Frequency Table


Step 2: Calculating Entropy for the classes (Play Golf)



In this step, you need to calculate the entropy for the Play Golf column and the calculation step is given below.

Entropy(PlayGolf) = E(5,9)



Step 3: Calculate Entropy for Other Attributes After Split



For the other four attributes, we need to calculate the entropy after each of the split.
  • E(PlayGolf, Outloook)
  • E(PlayGolf, Temperature)
  • E(PlayGolf, Humidity)
  • E(PlayGolf,Windy)

The entropy for two variables  is calculated using the formula.
(don't worry if about this formula, its really easy doing the calculation ☺


There to calculate E(PlayGolf, Outlook), we would use the formula below:


Which is the same as:

E(PlayGolf, Outlook)  = P(Sunny) E(3,2) + P(Overcast) E(4,0) + P(rainy) E(2,30

This formula may look unfriendly, but it is quite clear. The easiest way to approach this calculation is to create a frequency table for the two variables, that is PlayGolf and Outlook.
This frequency table is given below:

Table 3: Frequency Table for Outlook

Using this table, we can then calculate E(PlayGolf, Outlook), which would then be given by the formula below


Let's go ahead to calculate E(3,2)
We would not need to calculate the second and the third terms! This is because

E(4, 0) = 0
E(2,3) = E(3,2)
Isn't this interesting!!!


Just for clarification, let's show the the calculation steps
The calculation steps for E(4,0):


The calculation step for E(2,3) is given below
Time to put it all together.

We go ahead to calculate the E(PlayGolf, Outlook) by substituting the values we calculated from E(Sunny), E(Overcast) and E(Rainy) in the equation:

E(PlayGolf, Outlook)  = P(Sunny) E(3,2) + P(Overcast) E(4,0) + P(rainy) E(2,3)


E(PlayGolf, Temperature) Calculation

Just like in the previous calculation, the calculation of E(PlayGolf, Temperature) is given below. It
It is easier to do if you form the frequency table for the split for Temperature as shown.
Table 4: Frequency Table for Temperature

E(PlayGolf, Temperature)  = P(Hot) E(2,2) + P(Cold) E(3,1) + P(Mild) E(4,2)


E(PlayGolf, Humidity) Calculation

Just like in the previous calculation, the calculation of E(PlayGolf, Humidity) is given below. It
It is easier to do if you form the frequency table for the split for Humidity as shown.

Table 5: Frequency Table for Humidity



E(PlayGolf, Windy) Calculation

Just like in the previous calculation, the calculation of E(PlayGolf, Windy) is given below. It
It is easier to do if you form the frequency table for the split for Windy as shown.

Table 6: Frequency Table for Windy

Wow! That is so much work! So take break, walk around a little and take a glass of cold water.
Then we continue.
So now that we have all the entropies for all the four attributes, let's go ahead to summarize them as shown in below:
  1. E(PlayGolf, Outloook) = 0.693
  2. E(PlayGolf, Temperature) = 0.911
  3. E(PlayGolf, Humidity) = 0.788
  4. E(PlayGolf,Windy) = 0.892

Step 4: Calculating Information Gain for Each Split



The next step is to calculate the information gain for each of the attributes. The information gain is calculated from the split using each of the attributes. Then the attribute with the largest information gain is used for the split.

The information gain is calculated using the formula:

Gain(S,T) = Entropy(S) - Entropy(S,T)

For example, the information gain after spliting using the Outlook attibute is given by:

Gain(PlayGolf, Outlook) = Entropy(PlayGolf) - Entropy(PlayGolf, Outlook)


So let's go ahead to do the calculation

Gain(PlayGolf, Outlook) = Entropy(PlayGolf) - Entropy(PlayGolf, Outlook)
= 0.94 - 0.693 = 0.247


Gain(PlayGolf, Temperature) = Entropy(PlayGolf) - Entropy(PlayGolf, Temparature)
= 0.94 - 0.911 = 0.029

Gain(PlayGolf, Humidity) = Entropy(PlayGolf) - Entropy(PlayGolf, Humidity)
= 0.94 - 0.788 = 0.152

Gain(PlayGolf, Windy) = Entropy(PlayGolf) - Entropy(PlayGolf, Windy)
= 0.94 - 0.892 = 0.048

Having calculated all the information gain, we now choose the attribute that gives the highest information gain after the split.


Step 5: Perform the First Split



Draw the First Split of the Decision Tree
Now that we have all the information gain, we then split the tree based on the attribute with the highest information gain.

From our calculation, the highest information gain comes from Outlook. Therefore the split will look like this:

Figure 2: Decision Tree after first split


Now that we have the first stage of the decison tree, we see that we have one leaf node. But we still need to split the tree further.

To do that, we need to also split the original table to create sub tables.
This sub tables are given in below.

Table 7: Initial Split using Outlook


From Table 3, we could see that the Overcast outlook requires no further split because it is just one homogenous group. So we have a leaf node.

Step 6: Perform Further Splits



The Sunny and the Rainy attributes needs to be split

The Rainy  outlook can be split using either Temperature, Humidity or Windy.

Quiz 1: What attribute would best be used for this split? Why?
AnswerHumidity. Because it produces homogenous  groups.

Table 8: Split using Humidity

The Rainy attribute could be split using  High and Normal attributes and that would give us the tree below.


Figure 3: Split using the Humidity Attribute

Let't now go ahead to do the same thing for the Sunny outlook
The Rainy  outlook can be split using either Temperature, Humidity or Windy.

Quiz 2: What attribute would best be used for this split? Why?
AnswerWindy . Because it produces homogenous  groups.


Table 9: Split using Windy Attribute

If we do the split using the Windy attribute, we would have the final tree that would require no further splitting! This is shown in Figure4


Step 7: Complete the Decision Tree



The complete table is shown in Figure 4
Note that the same calculation that was used initially could also be used for the further splits. But that would not be neccessary since you could just look at the sub table and be able to determine which attribute to use for the split.

Quiz: What does each of he color represent in the tree? 
Leave your answer in the comment box below

Figure 4: Final Decision Tree



5. Final Notes


Now we have successfully completed the decision tree.
I think we need to celebrate with a bottle of beer!
This is how easy it is to build a decision three. Remember, the initial steps of calculating the entropy and the gain is the most difficult part. But after that, everything falls into place.

Do let me know if you have any challenges. Write me in the comment box below or in the form at the left of this page.


Thanks for reading!!!

Friday, 13 April 2018

Easy Free Python Tutorials With Step by Step Examples and Quiz

Hello!
If you are looking for a place to learn Python, this is the right place. Python would top the list as the most popular programming language from 2018 upwards.
So good to know that you would like to lear it.


The key to success is the practice it yourself and to make sure you do all the exercises in the series. Feel free to tell me if you have any challenges following this tutorial.

Take some time to go through test step by steps exercises ☺
  1. How to Setup Django 2.0 on Python 3.6 using virtualenv and pip (Try it!)
  2. How to Install Python on Windows 7 Easily (Try it!)
  3. How to Create a Simple Calculator in Python (Try it!)
  4. How to Write a Program to Solve Simultaneous Equation in Python Using Cramer's Rule (Try it!)
  5. How to Connect Python to MS Excel - Read and Write Data (Try it!)

Lesson Outline
1. Introduction to Python Programming
2. Downloading and Installing Python in Your Computer
3. Write Your First Python Program
4. Variables and Data Types in Python
5. Operators in Python
  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operator
6. Conditional Statements
  • If Statements
  • If-Else Statements
  • Nested If Statements
  • Final Notes
7. Loops in Python
  • Introduction to Loops in Python
  • While Loops
  • For Loops 
  • Nested Loops
  • Notes on Loops
8. Mathematics in Python
  • Working with Numbers
  • Converting Numbers
  • Maths Functions
  • Random Number Functions
  • Trigonometric Functions
  • Program to Solve Quadratic Equation
  • Final Notes

9. Working with Strings
  • Introduciton to Strings in Python
  • Escape Characters
  • String Special Operators
  • Formatting Strings

10. Concept of Lists in Python
  • Introduction to Python Lists
  • Accessing Values in Lists
  • Updating List values
  • Deleting Item from List
  • Basic List Operations

11. Introduction to Tuples in Python
  • Introduction to Tuples
  • Accessing Values in Tuples
  • Updating Tuple values
  • Deleting Item from a Tuple
  • Common Tuple Functions
  • Basic Tuple Operations

12. Dictionaries in Python
  • Introduction to Dictionaries
  • Accessing Values in Dictionaries
  • Updating Dictionary values
  • Deleting Item from a Dictionary
  • Dictionary Key Properties
  • Basic List Operations
  • Final Notes
13. Manipulating Date and Time Data in Python
  • Date and Time Concepts
  • How to get Current Time
  • How to Format Time
  • The Time Module
  • The Calander Module
  • Other Important Modules
  • Final Notes

14. Functions and Subroutines in Python
  • Introduction to Functions in Python
  • Function Definition Syntax
  • Calling a Function
  • Passing by Value and Passing by Reference
  • Function Arguments
  • Required Arguments
  • Keyword Argument

Thursday, 12 April 2018

15 Easy Free Java Tutorials With Step by Step Examples and Quiz

Hello! If you want to learn Java as a beginner to a Java Programming expert, this is the right place. The clue to success is: try it yourself!

 
So make sure you run the sample programs and also do the quiz in each of the sections.

Remember that if you have any challenge whatsoever, just let me know in the comment box below or on the left. I would get to you asap.


1. Java Programming Tutorials for Beginners: Introduction to Java and Installation of NetBeans
  • Basics of Java Program
  • What is Java Virtual Machine
  • What is an IDE
  • NetBeans Installation
  • Some Concepts to Know
  • Final Notes and Next Steps
2. Java Programming Tutorials for Beginners: Write Your First Java Program
  • Create a Netbeans Project
  • Understanding the NetBeans Environment
  • Create a New Project
  • Run the Program
  • Next Steps
3. Java Programming Tutorials for Beginners: Structure of a Java Program
  • Comments in Java
  • The package Keyword
  • The public class Keyword
  • The pulic static void main
  • System.out.println
  • The Semicolon (;)
  • Simple Quiz
  • Next Steps
4. Variables Data Types in Java
  • What are Variables
  • Integer Data Type
  • Double Data Type
  • Short and Float Data Type
  • Character Data Type
  • Java String Variables
  • Operator Precedence
  • Short Quiz
  • Final Notes and Next Steps
5. Conditional Statements in Java (if Statements)
  • The if Statement
  • Nested if Statement
  • if-else Statement
  • if-else-if Statement
  • Next Steps
6. Loops in Java
  • How Loops Work
  • For Loops
  • While Loops
  • Do While Loops
  • Exiting a Loop
7. Switch Statements in Java
  • How Switch Statements Work
  • Switch Statement Example
  • Comparing with if-else-if Statement
  • Notes on the Switch Statement
8. Arrays in Java
  • Array Declaration
  • Creating New Arrays
  • Using Foreach Loop
  • Passing Array as Methods
  • The Array Class in Java
9. Working with Strings
  • Creating Strings in Java
  • How to Get Lenght of String
  • Concatenating two Strings
  • Creating Format Strings
  • Useful String Methods
10. Reading and Writing to File
  • Introduction to Streams
  • Using FileOutputStream
  • Reading Data From File
  • Creating and Writing to File
  • Creating Directory in Java
  • Listing Directory Contents
11. OOP Concepts in Java 
  • Inheritance in Java
  • Overriding
  • Polymorphism in Java
  • Encapsulation
  • Multiple Inheritance and Interfaces
  • Data Abstraction : Abstact Classes in Java
  • Packages in Java
12. Inheritance in Java
  • Introduction to Inheritance in Java
  • Extends Keyword
  • The Super Keyword
  • Calling the SuperClass Constructor
  • The Instanceof Keyword
  • Types of Inheritance
13. Overriding in Java
  • Introduction to Overriding
  • Method Overriding
  • Difference between Overloading and Overriding
  • Using the Super Keyword
  • Final Notes

14. Polymorphism in Java
  • What is Polymorphism
  • Virtual Methods in Java
  • Polymorphism Example
  •  Dynamic Polymorphims
  • Static Polymorphism
15. Encapsulation
  • Introduction to Encapsulation in Java
  • Examples
  • Advantages
  • Final Notes on Encapsulation 

16. Multiple Inheritance and Interfaces
  • Introduction to Interfaces in Java
  • Interface Declaration
  • Implementing an Interface 
  • Extending Interfaces
  • Similarity of Interfaces and Classes
  • Difference Between Interfaces and Classes
  • Final Notes

17. Data Abstraction : Abstact Classes in Java
  • Introduction to Abstract Classes
  • Inheriting an Abstract Class
  • Abstract Methods
  • Final Notes
18. Packages in Java
  • What are Packages?
  • Creating a Package in Java
  • The Import directive
  • Directory Structure of Packages
  • The CLASSPATH System Variable
 Congratulations!!!!!!!!!!

Monday, 9 April 2018

RESTful Web Services Tutorial 8: Using Entity Framework With MVC - Database First

Hello, good to see you again! Thumbs up to you!

In this lesson we are going to use Entity Framework(EF) with MVC(Model-View-Controller) to carry out select, insert, update and delete operation. We would see the forms and tables generated easily for us, without writing codes.

 
Believe me, this is would be the easiest lesson so far in this series! I personally could not believe it when I saw it work like magic!

Let's do this!


We are going to cover the following:
  1. Create an API Web Service using MVC
  2. About the MVC Folders
  3. Generate the Models


1. Creat an Web Application Using Web API Template.


This is similar to the steps we followed in Tutorial 8 excep that if you get to the dialog box in Figure 1, you make sure that Web API is selected
Also make sure that the boxes for Web API and MVC is selected as shown

Figure 1: MVC Web API


After a few seconds,  the solution is generated as shown in Figure 2

Figure 2: Home Page of MVC Application

2. Learn about the folder structure


The folder structure for an MVC application always contains the folders: Model, View and Controller

Model: This folder contains the classes for your entities - which corresponds to tables in your database.

View: This Folder would contain subfolders which contains pages for each of entity for your application. For each of the table, there would be a folder. For each folder there would be five cshtml pages:
  • Create.cshtml
  • Details.cshtml
  • Edit.cshtml
  • Delete.cshtml
  • Index.cshtml

Controller: This folder contains the controller files for each of the the model (table). The controller file controls how the data from the table is access and displayed on a web page.

For now, these are the three folders you need to understand very clearly. This is because this same concepts is used in MVC architecture for other platforms like Java(using Eclipse IDE or any other IDE)

3. Generate the Models


Before you continue with this step, make sure you have create the Employee database in SQL Server.
Right-click on your project and Add new Item.
Choose Data and Select ADO.Net Entity Data Model

Figure 3: ADO.Net Entity Data Model




Give it a name and Click Add. The Entity Data Model Wizard is displayed as shown in Figure 3
Figure 4: EF Design from Database


Make sure that the EF Designer From database is selected. Click on Next to display the Database Connection definition step.
Figure 5:Choose Database Connection

Click on New Connection and specify the New Connection properties. In Figure 5, the Connection Properties have been defined.


Figure 6:Connection Properties Definition


After defining the new Connection, Click OK, then Click Next.
Click on Next again. When you get the the last step of the Wizard, Select Tables as shown in Figure 7.
 
Figure 7: Entity Data Model - Select Table


Click Finish. The class diagram is generated as shown in Figure8


 Figure 8: Generated Class Diagram





Examine the Classes generated. Expand the EmployeeModel.edmx to view the classes generated for each of the tables.



   public partial class Address
    {
        public Address()
        {
            this.Employees = new HashSet<Employee>();
        }
    
        public int Id { get; set; }
        public string Street { get; set; }
        public string Number { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public Nullable<int> CountryId { get; set; }
    
        public virtual ICollection<Employee> Employees { get; set; }
    }
Listing 1: Generated Class Address

For example, the generated class for the Address table is given in Listing 1. Isn't this amazing! All codes written for us. Thanks to Entity Framework!.





Friday, 6 April 2018

Series of Easy Tutorials on Bot Framework (How to Create Intelligent Bots using MS Cognitive Services)

Hello! So good to know that you have interest in learning. Thumbs up to you!

 

Remember that if you have any difficulty following these tutorials, you could metion it in the comment box below or in the form to the left of this page that says "Your opinion matters!. Then I could get back to you to give more assistance.

Bot Framework Tutorials 1 - Introduction to Microsoft Bot Framework

  1. What is Bot Framework? 
  2. What is a Bot? 
  3. What is Bot Builder?
  4. Tools You Need to Build a Bot
  5. Final Notes

Bot Framework Tutorials 2 - Create Your First Chat Bot in Azure(Step by Step) 
  1. How Bot Frameworks Work?
  2. What you need for this Demo
  3. Step-by-Step Procedure
  4. Final Notes
  5. Next Steps

Bot Framework Tutorials 3 - Understanding Bot Templates in Azure
  1. What are Bot Templates
  2. Basic Template
  3. Form Template
  4. Language Understanding 
  5. Question and Answer
  6. Proactive
  7. Final Notes

Bot Framework Tutorials 4 - How to Create a Question and Answer Bot in Azure
  1. What is a Question and Answer Bot
  2. Understanding LUIS
  3. The QnaMaker
  4. Steps Build a QnA Bot
    • Step 1: Create the Question and Answer Knowledgebase
    • Step 2: Create New Qna Service
    • Step 3: Create  a Question and Answer Bot
    • Step 4: Link the QnA Bot to the QnA Service
    • Step 5: Test The Bot
  5. Final Notes and Next Step

Bot Framework Tutorials 5 - Training a Question and Answer Bot in QnAMaker 
  1. Examine the Base Questions
  2. Add Your own questions
  3. Create a QnaServer in qnamaker.ai
  4. Test the Service
  5. Train Your Service
  6. Quiz for You
  7. Publish and Test  The Service
  8. Create a New Question and Answer Bot in Azure
  9. Final Notes and Next Steps


.Net REST Web Services Easy Tutorials (How to Build RESTful APIs)

Good to know you are ready to learn! Be sure you are in the right place.

Find below series of tutorials on building RESTful Web Services in .Net. These tutorials contain examples and sample codes that can help you to practice on your own.

RESTful Web Services Tutorial 1: Creating a RESTful API in Visual Studio(C# .Net)
Learn how to create a RESTful API from the scratch using Visual Studio in few easy steps. And you can follow these these lesson with no knowledge of programming.
More...

RESTful Web Services Tutorial 2: Setting up a REST Clinet (Advanced REST Client)
In this tutorial, you learn how to download and set up REST Client for free on your computer. REST Client makes it easy to test REST Web Services to make sure they comply with the REST Architecture. See Richarson's Maturity Model.
More..




RESTful Web Services Tutorial 3: Creating and Calling POST, PUT and DELETE Methods
In this tutorial, you learn how to Create the POST, PUT and DELET Methods in Visual Studio using C# code. You need to complete Tutorial 1 2 to be able to follow this tutorial.
More...

RESTful Web Services Tutorial 4: Testing the REST APIs Using Advanced REST Client
In this tutorial, you will get used to the Advanced REST Client environment and learn how to us ARC to test the web services you created in Visual Studio.
More...

RESTful Web Services Tutorial 5: Working wing MS SQL Database (Create the Employee Database)
In this tutorial, you will learn how to use MS SQL Server Management Studio to set up a database.
More..

RESTful Web Services Tutorial 6: Creating/Generating and entity Framework Class Diagram in Visual Studio
In this tutorial you will be learn a bit of Entity Framework and how to generated class diagrams and class files automatically from the database created in SQL Server.
More...

RESTful Web Services Tutorial 7: Working With Databases (Inserting a record into the database using DBContext)
In this tutorial, you will learn how to create a function to insert a record into the database from Visual Studio using DBContext.
More...

RESTful Web Services Tutorial 8: Using Entity Framework With MVC - Database First
In this tutorial, you will learn about Entity Framework with MVC and how to create an MVC application that would generate classes to access database tables from SQL Server.



Wednesday, 4 April 2018

Day 6: Handling Date and Time Data Types in C#

Hello, good to know that you are making fast progress.
Welcome to day 6 of ASP.NET in 24 days!

Today, we are going the learn how to handle date and time data types in C# as well as conversions.

We would cover the following
  1. Using DateTime type
  2. Creating an new date using the DateTime constructor
  3. Declaring date data type
  4. Converting to a date using Convert.toDateTime() 
  5. Converting Date to a String
  6. Getting Today’s date and time 
  7. Extracting Day, Month and Year from Date
  8. About TimeSpan Data Type 
  9. Final Notes
Note: To run the programs in this lesson, you need to copy the code and use it to replace the main function.




1. Using DateTime type


In C# a DateTime data type is a struct type that represents an instant of time.
The DateTime is a value type that represents dates and times values that range from:
00:00:00, January 1, 0001 to
11:59:59, December 31, 9999

A particular data is the number of ticks since 00:00:00 January 1, 0001. This are just some basic theory you need to just have in mind


2. Creating an new date using the DateTime constructor


  • You can create a new datetime object in any of the following ways:
  • Calling the DateTime constructure and specifying the arguments
  • Converting a string representation to a datetime using inbuilt functions

You can test these two methods using the code below.Create a console application, then copy and run the code snippet below.


3. Declaring date data type


To declare a DateTime object, you simply using the sytax

DateTime mydate = new DateTime()

In this case, the variable mydate is declared as a DateTime object but has not been assigned a value yet.


4. Converting to a date using Convert.toDateTime()


One of the ways to convert a value to a DateTime value is using the Convert.ToDateTime() function. I used this method most of the time.
You can basically convert any other type to DateTime() type. Run the following code snippet to see how it works.


        static void Main(string[] args)
        {
            Program pr = new Program();
            pr.UsingConvert();
        }

        public void UsingConvert()
        {
            DateTime mydate = Convert.ToDateTime(1000);
            Console.WriteLine();

            Console.Read();
        }
Listing 1.0: Using the Convert.ToDate() function (doesn't work!)

It doen't work! So don't use it
It is however inclued in the C# documentation;


5. Converting Date to a String


You can convert a string expression to a DateTime type using any of the following:
Parse(): Converts a string to its equivalent DateTime value
ParseExact(): This function converts a string to DateTime, but the string needs to match the exact date format, or else, there would be an error.
TryParse(): Converts string to DateTime but returns a value to indicate if the conversion succeeded or not.
TryParseExact: Converts a string to DateTime. The string format much match the date format and also value is returned to indicate success or failure

Run The code snippet below and try to understand how it works


        static void Main(string[] args)
        {
            Program pr = new Program();
            pr.UsingParse();
        }

        public void UsingParse()
        {
            string dateInput = "Jan 1, 2018";
            DateTime myDate = DateTime.Parse(dateInput);
            Console.WriteLine(myDate);
            // DISPLAYS THE DATE IN THE FORMATE 1/1/2018 12:00:00 AM
        }
Listing 2.0: Using the Parse Function

The listing 2.0 shows the convertion to DateTime() using Parse().
Quiz: Try to modify the code to use other Parse functions you have learnt here.


6. Getting Today’s date and time


There are many ways you can get the current date and time using the C# code:
  • DateTime.Today: Returns the current date
  • DateTime.Utc.Now.Date: Returns the current date
  • DateTime.Now.ToString("HH:mm:ss");
  • DateTime.Today.ToString("dd-MM-yyyy");

Try out all this methods by runing the code snippet below.


        static void Main(string[] args)
        {
            Program pr = new Program();
            pr.WorkingWithDate();
        }

        public void WorkingWithDate()
        {
          Console.WriteLine(DateTime.Today); //Returns the current date
          Console.WriteLine(DateTime.UtcNow.Date); //Returns the current date
          Console.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
          Console.WriteLine(DateTime.Today.ToString("dd-MM-yyyy"));
          DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        }
Listing 3.0: Getting Current Date and Time



7. Extracting Day, Month and Year from Date


You can extract the day, month or year part of a given date. When they are extracted, you can use then either as string or any other datatype. Here we assume we extract them as string.
So, the Listing 4.0, gives the code snippet that does the splitting. It is very clear and easy to understand. Run it and make sure you understands how it works.


        static void Main(string[] args)
        {
            Program pr = new Program();
            pr.SplitingDates();
        }

        public void SplitingDates()
        {
            String myDate = DateTime.Now.ToString(); //GET THE CURRENT DATE
            DateTime datevalue = (Convert.ToDateTime(myDate.ToString())); //CONVERTS THE myDate to a DateTime TYPE

            String dy = datevalue.Day.ToString();
            String mn = datevalue.Month.ToString();
            String yr = datevalue.Year.ToString();

            Console.WriteLine("The day is: " + dy);
            Console.WriteLine("The month is: " + mn);
            Console.WriteLine("The year is: " + yr);
        }
Listing 4.0: Extracting Day, Month and Year from a date




8. About TimeSpan Data Type


According the the msdn documentation, a TimeSpan represents a time interval.
Think of TimeSpan as a diffrence in time. When you subtract or add two dates, the result you have will be a TimeSpan. That is why it is called 'a time interval'.

Just like a Date contains day, month and year, a TimeSpan contains the following:

  • Days
  • Hours
  • Milliseconds
  • Minutes
  • Second

The Hours property of TimeSpan represents whole hours, while the TotalHours property represents whole and fractional hours of the TimeSpan. 
How TimeSpan works is illustrated in Listing 5.0. Please try to make sure you copy and run the code:


static void Main(string[] args)
        {
            Program pr = new Program();
            pr.UsingTimeSpan();
        }

        public void UsingTimeSpan()
        {
            TimeSpan span = DateTime.Now - DateTime.Now.Date;
            int days = span.Days;
            int hours = span.Hours;
            int mins = span.Minutes;
            int seconds = span.Seconds;
            int milisecs = span.Milliseconds;

            Console.WriteLine("Days: " + days);
            Console.WriteLine("Hours: " + hours);
            Console.WriteLine("Minutes: " + mins);
            Console.WriteLine("Seconds: " + seconds);
            Console.WriteLine("Milliseconds: " + milisecs);
        }
Listing 5.0: Using TimeSpan in C#


9. Final Note


Congrats if you have come this far!
If you encoutered any challenges ple mention it in the comment box below and someone would give you the needed assistance.