Home

Introduction

 

Fundamentals

 

Introduction

 

 

     
 
 

 

   
   
 

Previous Copyright © 2015 FunctionX Next

Home

Date and Time Values

 

Fundamentals of Dates and Times

 

Introduction

The F# language doesn't have its own data type for date and time values. Instead, it relies on both the operating system and the .NET Framework. To assist the users with requesting date and time values, the .NET Framework provides various Windows controls, namely the month calender, the date/time picker, and the masked text box.

In Microsoft Windows, date and time values are managed through a structure named SYSTEMTIME. In the .NET Framework, dates and times are managed using a structure named DateTime.

To create a date or a time value, you can first declare a DateTime variable. To assist you with initializing the variable, the DateTime structure is equipped with various constructors.

The default constructor allows you to create a date or a time object without specifying its details. This would be done as follows:

open System

let tm = new DateTime()

If yo want to explicitly indicate that the variable is of type DateTime, on the right side of the name of the variable you are declaring, type : DateTime. Here is an example:

open System

let tm : DateTime = new DateTime()

After declaring a DateTime variable and initializing it, it holds all necessary pieces of information about its date and its time values.

The Default Date and Time Values

The default constructor of the DateTime structure initializes the date to January 1st, 0001 and the time at midnight (01:01:01). This also means that the lowest date and time values that a DateTime object can hold is January 1st, 0001 at 00:00:00. This value is represented by the MinValue constant member of the DateTime structure. The highest date and time that a DateTime object can hold in the structure is called MaxValue and it is set at December 31, 9999.

Fundamental Date Values

 

Date Creation

A date is a technique of identifying a period using three numbers: the year, the month, and the day. Each is an integer value. If you know the values you want to use to create or specify a date value, when declaring a DateTime variable, you can use the following constructor:

new : 
        year:int * 
        month:int * 
        day:int -> DateTime

Here is an example of creating a date:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let mcFundamentals : MonthCalendar = new MonthCalendar()
mcFundamentals.Location <- new Point(12, 12)

mcFundamentals.SelectionStart <- new DateTime(1986, 10, 15)
mcFundamentals.SelectionEnd <- new DateTime(1986, 10, 15)
exercise.Controls.Add mcFundamentals

do System.Windows.Forms.Application.Run exercise

Fundamental Date Values

Converting a String to Date

Before displaying a DateTime value in your application, you can first convert it to a string. You have two options. In F#, to convert a value to a string, precede it with string. Here is an example:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let txtDate : TextBox = new TextBox()
txtDate.Location <- new Point(12, 12)
txtDate.Width <- 120

txtDate.Text <- string (new DateTime(1960, 1, 1))

exercise.Controls.Add txtDate

do System.Windows.Forms.Application.Run exercise

Converting a String to Date

To support value conversion in the .NET Framework, the DateTime structure is equipped with the ToString() method that is overloaded with various versions. One of the versions takes no argument and its syntax is:

abstract ToString : unit -> string  
override ToString : unit -> string

If you call this version of the method, the compiler uses a default format depending on the language set on the user's computer. If you want to control how the date should be rendered, you can use the version of the ToString() method that takes as argument a String value.

Rules of Date Formats

The computer uses two main ways to display date values. These categories are based on the language used by a computer. For example, most user computers in the United States use a standard known as US English. This standard commands how a date value displays in the US. Each category uses specific characters to represent its value:

Format Description

MM

The double M (in uppercase) string gets the numeric value of the month from 1 to 12. If the number is less than 10, it would display with the leading 0. Here is an example:

open System

let date : DateTime = new DateTime(2002, 4, 22)
let strMonth : string = date.ToString("MM")

It the number is higher than 9, it would display so.

MMM

The triple M as MMM (in uppercase) gets the short name of the month. In US English, the short names of months are Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. Here is an example:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let date : DateTime = new DateTime(1998, 1, 12)
let strMonth : string = date.ToString("MMM")

let txtDate : TextBox = new TextBox()
txtDate.Location <- new Point(12, 12)
txtDate.Width <- 120

txtDate.Text <- strMonth

exercise.Controls.Add txtDate

do System.Windows.Forms.Application.Run exercise

This would produce:

Converting a String to Date

MMMM

The quadruple M as MMMM (in uppercase) gets the long name of a month as defined by the operating system of the user's computer. Here is an example:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let date : DateTime = new DateTime(2004, 10, 22)
let strMonth : string = date.ToString("MMMM")

let txtDate : TextBox = new TextBox()
txtDate.Location <- new Point(12, 12)
txtDate.Width <- 120

txtDate.Text <- strMonth

exercise.Controls.Add txtDate

do System.Windows.Forms.Application.Run exercise

This would produce:

Converting a String to Date

dd

The double d gets the numeric day of the month. If the number is less than 10, it would display with a leading 0. Here is an example:

open System

let date : DateTime = new DateTime(2002, 4, 2)
letstrDay : string = date.ToString("dd")
yy

The double y is used to get the numeric year with the last two digits. Here is an example:

open System

let date : DateTime = new DateTime(2002, 4, 2)
let strYear2Digits : string = date.ToString("yy")
yyyy

The yyyy string is used to get all four digits of a year. Here is an example:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let date : DateTime = new DateTime(2004, 10, 22)
let strYear : string = date.ToString("yyyy")

let txtDate : TextBox = new TextBox()
txtDate.Location <- new Point(12, 12)
txtDate.Width <- 120

txtDate.Text <- strYear

exercise.Controls.Add txtDate

do System.Windows.Forms.Application.Run exercise

This would produce:

Converting a String to Date

If the year was provided with two digits, such as 98, it would still be produced with 4 digits. Consider the following example:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let date : DateTime = new DateTime(98, 4, 2)
let strYear4Digits  : string = date.ToString("yyyy")

let txtDate : TextBox = new TextBox()
txtDate.Location <- new Point(12, 12)
txtDate.Width <- 120

txtDate.Text <- strYear4Digits 

exercise.Controls.Add txtDate

do System.Windows.Forms.Application.Run exercise

This would produce:

Converting a String to Date

 

Date Formats

 

The Computer's System of Displaying Dates

To display a date in an application, by default, the compiler checks the Regional Options of the Control Panel. To see the options, from the Control Panel, you can double-click Regional or Language Option. From the Regional Options tab of the Regional or Language Option dialog box, you can click Customize... In the Customize Regional Options dialog box, click Date.

Getting a Date Value From a Date/Time Object

You may have noticed that, by default, a DateTime variable always produces both a date and a time. In some cases, you will be interested in only the date portion. To get a date value, you can call the DateTime.ToString() method that takes a String as argument and apply some rules:

Format Description
  Empty Space: Between the components of a date value, you are allowed to leave empty spaces if you want.
Don't pass an empty space to the ToString() method.
, Comma: To separate the sections of a date value, you can use the comma.
Don't pass a comma by itself to the ToString() method.
/ Date Separator: The compiler refers to the Control Panel to identify this character. In US English, the forward slash is used to separate the portions of a date:

Customize Regional Options

Don't pass the forward slash by itself to the ToString() method.

Others: - . Dash and Others: Besides the forward slash, the user's computer may allow other characters. For example, in US English, the "-" can be used. You can check the available characters in the Date Separator combo box of the Date tab of the Customize Regional Options of the Control Panel.
Don't pass any of these characters by itself to the ToString() method.

The other characters and their combinations (MM, MMM, MMMM, dd, yy, and yyyy) are used as we reviewed them. Here are examples of displaying date formats:

open System
open System.Drawing
open System.Windows.Forms

let date : DateTime = new DateTime(2004, 10, 23)

let mutable result = sprintf "Date and Time:  %A" date

MessageBox.Show result |> ignore

result <- sprintf "Date: %A" (date.ToString("M/d/yyyy"))
MessageBox.Show result |> ignore

result <- sprintf "Date: %A" (date.ToString("M/d/yy"))
MessageBox.Show result |> ignore

result <- sprintf "Date: %A" (date.ToString("MM/dd/yy"))
MessageBox.Show result |> ignore

result <- sprintf "Date: %A" (date.ToString("MM/dd/yyyy"))
MessageBox.Show result |> ignore

result <- sprintf "Date: %A" (date.ToString("yy/MM/dd"))
MessageBox.Show result |> ignore

result <- sprintf "Date: %A" (date.ToString("yyyy-MM-dd"))
MessageBox.Show result |> ignore

result <- sprintf "Date: %A" (date.ToString("dd-MMM-yy"))

This would produce:

  Getting a Date Value From a DateTime Object  
Getting a Date Value From a DateTime Object Getting a Date Value From a DateTime Object Getting a Date Value From a DateTime Object
Getting a Date Value From a DateTime Object Getting a Date Value From a DateTime Object Getting a Date Value From a DateTime Object

The Short Date

Instead of creating your own format, the Microsoft Windows operating system provides two names that can be used to identify a date. A date is referred to as short if it includes (only) the numeric portions of the month and the day of a date value. The operating system follows the rules we have reviewed so far for the numbers and the Date Separator. The possible formats of a short date can be seen in the Short Date Format combo box of the Date tab of the Customize Regional Options of the Regional and Language Settings of the Control Panel:

To get the Short Date of a DateTime object, pass a "d" (one d in lowercase) string to the ToString() method. Here is an example:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let date : DateTime = new DateTime(2004, 10, 22)
let strMonth : string = date.ToString("d")

let txtDate : TextBox = new TextBox()
txtDate.Location <- new Point(12, 12)
txtDate.Width <- 120

txtDate.Text <- strMonth

exercise.Controls.Add txtDate

do System.Windows.Forms.Application.Run exercise

This would produce:

Converting a String to Date

The Long Date Format

A date is referred to as long if it includes the name of the month and the day of the week of a date value. This is called the Long Date Format. To get the Long Date of a date, pass a "D" (one d in uppercase) string to the ToString() method of a DateTime object. Here is an example:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let date : DateTime = new DateTime(2004, 10, 22)
let strMonth : string = date.ToString("D")

let txtDate : TextBox = new TextBox()
txtDate.Location <- new Point(12, 12)
txtDate.Width <- 140

txtDate.Text <- strMonth

exercise.Controls.Add txtDate

do System.Windows.Forms.Application.Run exercise

This would produce:

Converting a String to Date

To produce the result, the compiler refers to the Long Date Format combo box of the Customize Regional Options of the Control Panel. The user can change the format by selecting one from the combo box:

Date Regional

Based on the default settings of a computer used in US English, the above program would produce:

Other Date Formats

The .NET Framework provides other formats, not regularly used but available. To get the name of a month and the year value of a DateTime object, both separated by an empty space, pass a single M (uppercase) as string to the ToString() method of a DateTime object. Here is an example:

open System

let date : DateTime = new DateTime(2004, 10, 23)
let strDate = date.ToString("M")

To include a comma in the result, pass a single y (lowercase) as string to the ToString() method of a DateTime object. Here is an example:

open System

let date : DateTime = new DateTime(2004, 10, 23)
let strDate = date.ToString("y")

Characteristics of Date Values

 

The Leap Year

One of the operations performed on date values is to find out whether the year value of a date is a leap year. Fortunately, the static IsLeapYear() method of the DateTime structure can be used to perform this operation. The syntax of this function is:

static member IsLeapYear : 
        year:int -> bool

This method takes an integer argument and examines it. If the argument, which must be a valid year number, is a leap year, the method returns true; otherwise, it would return false. Here are two examples:

open System
open System.Windows.Forms

let mutable date : DateTime = new DateTime(1988, 10, 6)
MessageBox.Show(sprintf "%d was a leap year: %b" date.Year (DateTime.IsLeapYear(date.Year))) |> ignore

date <- new DateTime(1990, 8, 12)
MessageBox.Show(sprintf "%d was a leap year: %b" date.Year (DateTime.IsLeapYear(date.Year))) |> ignore


printfn "%d was a leap year: %b" date.Year (DateTime.IsLeapYear(date.Year))

date <- new DateTime(1990, 8, 12)
printfn "%d was a leap year: %b" date.Year, (DateTime.IsLeapYear(date.Year))

This would produce:

The Leap Year         The Leap Year

The Day of the Week

The DateTime structure is equipped with a property that can be used to retrieve the day of the week for a given date. The property is named DayOfWeek. The values are stored in the DayOfWeek enumeration. Here is an example:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 177),
                                             StartPosition = FormStartPosition.CenterScreen)

let date : DateTime = new DateTime(2004, 10, 21)

let txtDate : TextBox = new TextBox()
txtDate.Location <- new Point(12, 12)
txtDate.Width <- 120

txtDate.Text <- string date.DayOfWeek

exercise.Controls.Add txtDate

do System.Windows.Forms.Application.Run exercise

This would produce:

The Day of the Week

Operations on Date Values

 

A Time Span

Many applications need date values to perform their routine operations. Common operations include adding days to a date, subtracting months from a date, adding years, comparing dates to find out whether one occurs before another, finding out if a payroll falls on a holiday, etc. To perform some of these operations, a unit called an interval is considered as part of a date. A date interval can be the number of days, months, or years that have elapsed, or would elapse, from one starting date to another ending date. Once you have specified this interval, you can then apply it to a date with the operation of your choice.

To support the ability to perform operations on dates, the .NET Framework is provides the TimeSpan structure. This structure is equipped with various members that would be applied on the TimeSpan structure. The value produced by this structure is then applied to a DateTime object. To create a date interval, declare a TimeSpan variable and initialize it with the desired value(s). To make this possible, the TimeSpan structure is equipped with various constructors.

Adding and/or Subtracting Days

With the DateTime structure, you can add some days to an existing date or subtract some days from a date value. To support this, the DateTime structure is equipped with the AddDays() method. Its syntax is:

member AddDays :
        value:float -> DateTime

Here is an example of calling this method:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 217),
                                             StartPosition = FormStartPosition.CenterScreen)
let startDate : DateTime = new DateTime(1988, 10, 6)

let mcFundamentals : MonthCalendar = new MonthCalendar()
mcFundamentals.Location <- new Point(12, 12)

mcFundamentals.SelectionStart <- startDate
mcFundamentals.SelectionEnd <- startDate
exercise.Controls.Add mcFundamentals

let btnAddDays = new Button(Text = "Add Days",
                            Location = new Point(66, 183),
                            Size = new System.Drawing.Size(75, 23))

let btnAddDaysClick e =
    // This will be used to add 8 days to the previous date
    let endDate : DateTime = startDate.AddDays 8.00

    // And display it
    mcFundamentals.SelectionStart <- endDate
    mcFundamentals.SelectionEnd <- endDate

btnAddDays.Click.Add btnAddDaysClick
exercise.Controls.Add btnAddDays

do System.Windows.Forms.Application.Run exercise

This would produce:

Adding and/or Subtracting Days Adding and/or Subtracting Days

If you pass a positive value to the DateTime.AddDays() method, a number of days is added to the DateTime variable. If you want to subtract some days from a date, pass the argument with a negative value. This method is able to figure out the year before, the month before, the day before, the day after, the month after, and the year after the designated date.

One of the constructors of the TimeSpan structure takes four arguments. Its syntax

new : 
        days:int * 
        hours:int * 
        minutes:int * 
        seconds:int -> TimeSpan

The first argument of this constructor represents the number of days. If you are planning to add a number of days to a date, pass a positive integer as the first argument. If you want to subtract a date, pass a negative value. If you want to add only a number of days, pass only this argument.

After creating a TimeSpan object, you can call the Add() method of the DateTime structure to add a date value. This would produce a new DateTime object that is the resulting value. Here are examples:

open System
open System.Drawing
open System.Windows.Forms

let exercise = new System.Windows.Forms.Form(Text = "Date Values",
                                             MaximizeBox = false,
                                             ClientSize = new System.Drawing.Size(203, 217),
                                             StartPosition = FormStartPosition.CenterScreen)

let mcFundamentals : MonthCalendar = new MonthCalendar()
mcFundamentals.Location <- new Point(12, 12)

mcFundamentals.SelectionStart <- DateTime.Today
mcFundamentals.SelectionEnd <- DateTime.Today
exercise.Controls.Add mcFundamentals

let btnAddDays = new Button(Text = "Add Days",
                            Location = new Point(12, 183),
                            Size = new System.Drawing.Size(75, 23))
                            
let btnAddDaysClick e =
    let currentDate = mcFundamentals.SelectionStart

    let ts : TimeSpan = new TimeSpan(172, 0, 0, 0)
    let date : DateTime = currentDate.Add ts

    mcFundamentals.SelectionStart <- date
    mcFundamentals.SelectionEnd <- date

btnAddDays.Click.Add btnAddDaysClick
exercise.Controls.Add btnAddDays

let btnSubtractDays = new Button(Text = "Subtract Days",
                            Location = new Point(95, 183),
                            Width = 95)
exercise.Controls.Add btnSubtractDays

let btnSubtractDaysClick e =
    let currentDate = mcFundamentals.SelectionStart

    let ts : TimeSpan = new TimeSpan(-10, 0, 0, 0)
    let date : DateTime = currentDate.Add ts

    mcFundamentals.SelectionStart <- date
    mcFundamentals.SelectionEnd <- date

btnSubtractDays.Click.Add btnSubtractDaysClick
exercise.Controls.Add btnSubtractDays

do System.Windows.Forms.Application.Run exercise

This would produce:

Adding and/or Subtracting Days Adding and/or Subtracting Days Adding and/or Subtracting Days

Adding or Subtracting Months to a Date

To add a number of months to a date, the DateTime class is equipped with a method named AddMonths(). Its syntax is:

member AddMonths : 
        months:int -> DateTime

This method takes one argument as the number of months to be added or subtracted. If you pass the argument with a positive value, the months are added to the date. If you pass a negative value, the number of months is subtracted from the date.

Adding or Subtracting Years to a Date

To get the date a few years before or after a known date, you can add years to, or subtract years from, a known date. To support this operation, the DateTime class provides a method named AddYears(). Its syntax is:

member AddYears : 
        value:int -> DateTime

The argument passed to the method is the number of years. A positive value (or a negative value) adds (or subtracts) the number of years to (or from) the date.

Logical Operations on Dates

Using the logical operators we reviewed for primitive types, you can compare the values of dates for equality, differences, lower or greater values. To support these operations, the DateTime structure has the logical operators configured.

To compare two dates, apply the desired Boolean operator the same day you would two variables of primitive types.

Time

 

Introduction

As defined earlier, the time is a value used to identify the number of units that have elapsed since a starting period, called midnight, of a day. A day is made of 24 non-spatial divisions; each one of these divisions is called an hour. An hour is made of 60 fractions and each one of these fractions is called a minute. A minute is divided in 60 parts, each called a second. As done with dates, most of the operations performed on time values are centered around the DateTime structure.

The rules used by the computer for time display can be seen in the Customize Regional Options dialog box. To access it, in the Control Panel, you can double-click Regional and Language Options. In the Regional Options tab of the Regional and Language Options dialog box, you can click Customize. In the Customize Regional Options, you can click Time:

Customize Regional Options

In US English, the symbol to separate the hour and the minute is the colon ":". An example would be: 08:25. In the same way, in US English, the character used to separate the minute and the second is the colon ":". An example would be: 08:25:44. In many cases, unless necessary, the second is not represented in a time value.

The time of a day can be considered as a value of 24 hours or the day can be considered as two fractions of 12 hours each. There is a period in the middle of day time called noon. It divides the 24-hour day in two parts, each consisting of 12 hours. The noon period is positioned 12 hours after midnight. The period that goes from midnight to the middle of day time is represented by the expression AM. The period from noon to midnight is represented by the PM expression. When a DateTime object includes an AM or PM but of unknown value, the section is represented as AM/PM and this expression is written on the right side of the seconds. To separate the seconds and the AM/PM, you (as well as the compiler) leave a one-character empty space after the seconds.

Creating a Time Value

The time portion of a DateTime value can be declared and manipulated as a value. To create a time value, you can declare a DateTime variable using the following constructor:

new : 
        year:int * 
        month:int * 
        day:int * 
        hour:int * 
        minute:int * 
        second:int -> DateTime

If you are more concerned about the time, the first, second, and third arguments are not important. You can pass each as 1. In this case, the date would be set as January 1, 0001. The other three arguments represent the components of a time value.

The minutes value must range from 0 to 59; otherwise, an error would be produced. The seconds value must be between 0 and 59 or the program would cause an error.

When initializing a date or time variable using this constructor, the hour value must be between 0 and 23. Any other value outside of this range will cause an error. If the hour portion has a value between 0 and 11, the time is set in the morning with the AM in the AM/PM section. Here is an example:

open System

let time : DateTime = new DateTime(1, 1, 1, 10, 24, 52)

If the hour portion is between 12 and 23, the time is set in the afternoon. When displaying it, the compiler, by default, calculates and displays the 0 to 12 portion and then displays PM in the AM/PM section. Here is an example:

open System

let time : DateTime = new DateTime(1, 1, 1, 16, 8, 44)

In special cases, you may want to use the milliseconds of a time value. When declaring and initializing the variable, you can use the following constructor:

new : 
        year:int * 
        month:int * 
        day:int * 
        hour:int * 
        minute:int * 
        second:int * 
        millisecond:int -> DateTime

The milliseconds must range from 0 to 999. If you do not know the millisecond value, you can provide it as 0.

Retrieving a Time Value

In some of your applications, you may want the user to supply a time value. As mentioned for the date, there are rules that you, the computer, and the user must follow to apply a valid formula. As mentioned already, the compiler refers to the computer to find out what a date looks like. A valid time can follow the format hh:nn AM/PM or hh:nn:ss or one of the valid combinations. When requesting a time from the user, in case the user is not familiar with the rules (and you should assume that the user doesn't know them), specify what formula the user should follow. Here is an example:

open System

printf "Enter a date (yyyy/mm/dd): "
let dateSubmitted = DateTime.Parse(stdin.ReadLine())

The Characteristics of a Time Value

 

The Components of a Time

By now, we have seen that a time value is made of the hour, the minute, the second, and the millisecond parts. These are values you can specify when creating a time object using one of the appropriate constructors of the DateTime structure. If you request a time value from the user or if the application itself will provide it, you can retrieve its components.

To get the hour portion of an existing DateTime object, you can access its Hour property. To retrieve the minute side of a time value, access its Minute property. If you want to know the second value of a DateTime variable, you can call its Second property. In the same way, you can get the millisecond value of a time by accessing its Millisecond property.

The Time of Day of a Date/Time Value

As seen so far, a DateTime variable always holds both a date and a time portions. In your program, you may want to get only the time of the variable. To support this, the DateTime structure is equipped with a property named TimeOfDay. This property produces the time value of an existing DateTime object. Here is an example of using it:

open System

let time : DateTime = new DateTime(2002, 4, 22, 16, 8, 44)

. . . time.TimeOfDay

Operations on Time Values

 

Converting a Time Value to a String

If you have a DateTime object, you can convert it to a String value. To do this, you can precede the name of the variable with string. Here is an example:

open System

let time : DateTime = new DateTime(2002, 4, 22, 16, 8, 44)
let strTime = string time

Also, the DateTime structure is equipped with a method named ToString. The default version of this method takes no argument and it simply creates a string out of a time value. Here is an example:

open System

let time : DateTime = new DateTime(2002, 4, 22, 16, 8, 44)
let strTime : string = time.ToString()

Notice that the value produced by the string includes both the date, the time and even the AM/PM section. In some cases, you would be interested only in either the date or the time. To support this type of operation, the DateTime structure has another overloaded version of the ToString() method that takes as argument a String value. When calling this method, there are rules you should/must follow.

Time Rules and Formats

Like dates, time values follow the Regional (and Language) Settings of Control Panel when they display. To make this display friendlier, Microsoft Windows provides the rules, through some characters, you can use to format a time:

Time

 The characters used to create a format are:

Format Used For Description
hh Hours An hour number from 0 to 23.
If the hour is less than 10, it would display with the leading 0 such as 08. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 5, 8, 37)
let strHour : string = time.ToString("hh")

If the hour is greater than 12, such as 15, 12 would be subtract from it and it would display with a leading 0, such as 05. Here is an example:

open System

let time : DateTime = new DateTime(2002, 4, 22, 15, 8, 37)
let strHour : string = time.ToString("hh")
HH Hours An hour number from 0 to 23.
If the hour is less than 10, it would display with the leading 0 such as 08. The effect is the same as seen for the hh format.
If the hour is greater than 12, such as 15, it would display with that value. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 15, 8, 37)
let strHour : string = time.ToString("HH")
mm Minutes A minute number from 0 to 59.
If the number is less than 10, it would display with the leading 0 such as 06. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 15, 8, 37)
let strMinute : string = time.ToString("mm")

If the number is greater than 9, it would display the same.

ss Seconds A second value from 0 to 59.
If the number is less than 10, it would display with the leading 0 such as 04. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 15, 8, 7)
let strSecond : string = time.ToString("ss")

If the number is greater than 9, it would display like that. 

tt
or
tttt
AM/PM Expression used to produce the AM or PM side of a time value. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 5, 8, 7)
let strAMPM : string = time.ToString("tt")

To create or format a (complete) time value, you must use a combination of characters:

Format Used For Description
: Separator The character separator for time values.
This character is set in the Regional (and Language) Settings of Control Panel.
Don't use this character by itself in a ToString() method.
h or H Hours An hour number from 0 to 23.
If the hour is less than 10, it would display without the leading 0.
Don't use the letter "h" or "H" by itself in a ToString() method
m Minutes A minute number from 0 to 59.
If the number is less than 10, it would display without the leading 0. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 15, 8, 37)
let strMinute string = time.ToString("h:m")

If the minute number is greater than 9, it would display as such.
Don't use the letter "m" by itself in a ToString() method.

mm Minutes A minute number from 0 to 59.
If the number is less than 10, it would display with a leading 0. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 15, 8, 37)
let : strMinute : string = time.ToString("h:mm")   

Don't pass "mm" by itself in a ToString() method

s Seconds A second value from 0 to 59.
If the number is less than 10, it would display without a leading 0. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 15, 8, 7)
let strSecond  : string = time.ToString("h:mm:s")

Don't pass "mm" by itself in a ToString() method

ss Seconds A second value from 0 to 59.
If the number is less than 10, it would display with a leading 0. Here is an example:
open System

let time : DateTime = new DateTime(2002, 4, 22, 15, 8, 7)
let strSecond  : string = time.ToString("h:mm:ss")

Don't pass "mm" by itself in a ToString() method

When combining these characters to create a format, you should abide by the rules of your language, such as US English. You should refer to the formula set in the Time property page of the Regional (and Language) Settings of Control Panel.

Comparison Operations On Time Values

As done for date values, you can compare time values to find out if one occurs before another or whether they occur at the same time. To support the comparisons, the DateTime structure is equipped with the Compare() method.

Combining Date and Time

 

The Current Date and Time

When a user starts a computer and while using it, it keeps a date and time values referred to as local date and time or system date and time. Depending on your application, at one time you may need to get one or both of these pieces of information. It is important to know that the computer, not you, controls this information (but you can programmatically change it if you want). To support both, the DateTime structure is equipped with a static property named Now. This property holds the year, the month, the day, the name of the day, the hour, the minute, and the second. Here is an example of calling it:

open System

sprintf "System Date and Time: %A" DateTime.Now

To get the current date of the computer, the DateTime structure provides a static property named Today. Here is an example:

open System

sprintf "Current Date: %A" DateTime.Today

Formatting Date and Time Combinations

Although the DateTime structure is equipped to produce default values of a date and time in combination, you can use the formats we have reviewed to create your own date, in the sequences of your choice, such as a time preceding a date, a value providing only the month and the minutes, etc.


Home Copyright © 2015, FunctionX Home