Lesson 14 - Working with Dates and Times

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article

Get GitHub Code

There are four primitive data types that you will be consistently working with throughout your C# programming career:

  • string

  • int

  • double

  • bool

In this lesson, you will be introduced to another data type that allows you to work with dates and times. It’s called DateTime, but unlike the previously mentioned simple data types, DateTime is a complex data type. It’s complex in that it is a class, defined in the .NET Framework class library, that itself is composed of a variety other data types. A DateTime variable (or object) contains within it, for example, three separate int variables called Second, Minute, and Hour, which hold those individual time values. Now, this topic – relating to classes, object-oriented programming, and the .NET Framework - is outside of the scope of this lesson. But it is worth noting up front the difference between complex and simple data types.

Step 1: Create a New Project

As always, you can either setup the Project and Default.aspx page, or use the provided code in the Before folder for this Lesson.

For this demonstration, create a new ASP.NET project and call it “CS-ASP_014.” Set up Default.aspx with the following Server Controls, and programmatic IDs:

  1. okButton

  2. resultLabel


Step 2: Create and Access a Variable of Type DateTime

In the okButton_Click event, create a DateTime variable, and set it to the current time, using the "Now" property:


When you hover over a property, such as the “Now” property in DateTime.Now, you will often find a helpful tip about what it represents:


Now that we have the current time, let’s try to output it by assigning it to resultLabel.Text:


This error informs us that we need to use a helper method to convert this variable type to a string. All you need to do to make the error disappear is convert it to a string using ToString(), and you can now run the application:



Step 3: Formatting Date Values Returned from DateTime.Now

Keep in mind that the formatting order shown here (Day/Month/Year, Hour/Minute/Second, AM/PM) is dependent on your Windows localization settings on your computer. There are other ways of formatting the current time, and there are a number of helper methods you can access to facilitate this. Go ahead and try a few of the “To” methods available to DateTime variables:


Write out these methods to see the different formatting results they produce (be sure to comment out the ones you are not currently testing to avoid getting a compilation error):






Test out these other helper methods, which require a ToString() appended on the end since each of these return values that are not of type string:








Here is what each of these methods, specific to DateTime, do:

  1. Returns a DateTime two days forward from the current DateTime.

  2. Returns a DateTime two months backward from the current DateTime.

  3. Returns the month, as an int, from the current DateTime.

  4. Returns a bool expressing if the current DateTime is at a point during daylight savings.

  5. Returns the day, as a string, from the current DateTime.

  6. Returns the day in the year, as an int, from the current DateTime.

Tip: You may have noticed that some of the helper methods above have helper methods that operate on them. This is a useful technique in C# called chaining that allows you to chain methods together. For instance, myValue.AddDays(2) will return a DateTime value. AddDays() performs one operation on the myValue variable, and once that operation is complete, ToString() takes myValue and converts it to a string. You can do this because each helper method is affecting the variable, performing multiple operations on it within a single line of code.

Step 4: Parsing a String into a DateTime via DateTime.Parse()

Next, let’s feed a particular date into a method that parses through it (performing an algorithm) and returns DateTime information it was able to parse from it:



Tip: The date here – 12/7/1969 – happens to be my birthday, which I know occurred on a Sunday. You may find it more interesting to input your own birthday to see what day you were born on.

Alternatively, you can also use the "new" keyword and initialize the DateTime by passing the values in between the parentheses:


Here, we’re setting the properties stored in myValue to:

  1. Year

  2. Month

  3. Day

  4. Hour

  5. Minute

  6. Second

You have many different ways of initializing the DateTime, and you can get a list of them by typing in the parentheses and using the up/down arrows on your keyboard to cycle through the variations:


This is a preview of both a special kind of method called a “Constructor,” as well as what is called “Constructor Overloading.” There isn’t anything very fancy about Constructors other than the fact that they are methods with the same name as the type they belong to. In this case, the Constructor DateTime() belongs to the DateTime value. They are used for initializing certain values determined by what’s written in the Constructor. Overloading, meanwhile, refers to variations of the same Constructor that have different initialization procedures. Don’t worry too much about understanding this at this point as the process will be made much clearer in subsequent lessons. Keep up the good work, you're doing great!

Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Please login or register to add a comment