Situation
You want to know how to output time (C#'s DateTime values) in different layouts, such as only the hours and minutes (7:15) or the time including milliseconds (7:15:49.375).

Programming example

using System;
using System.Drawing;
using System.Linq;
using PowerLanguage.Function;

namespace PowerLanguage.Indicator
{
    [UpdateOnEveryTick(false), SameAsSymbol(true)]
    public class Example_FormattingTimeOutput : IndicatorObject
    {
        public Example_FormattingTimeOutput(object _ctx) : base(_ctx) { }

        protected override void StartCalc()
        {
            ExecInfo.MaxBarsBack = 5;
            Output.Clear();
        }

        protected override void CalcBar()
        {
            if (Bars.LastBarOnChart)
            {
                Output.WriteLine("Bar time: {0:H:m}, previous bar time: {1}.",
                    Bars.Time[0],
                    Bars.Time[1].ToString("HH:mm:ss 'on date:' d-M-y"));

                DateTime timeNow = DateTime.Now;
                Output.WriteLine("The current time is: {0:HH:mm:ss.fff}.",
                    timeNow);
            }
        }
    }
}

Output of the programming example

The following text in the Output Window is generated by the indicator:

Bar time: 22:58, previous bar time: 22:06:00 on date: 19-9-14.
The current time is: 10:02:48.079.

The PowerLanguage .NET Editor Output Window

The PowerLanguage .NET Editor Output Window allows for conveniently and quickly outputting information, which is especially useful during the development of an indicator or trading strategy.

Text can be printed in any of the override methods (MultiCharts, 2013) and controlling the Output Window can be done with several methods (PowerLanguage .NET Help, n.d.):

  • Text is written to the Output Window with Output.Write(), while text with a line break is printed with Output.WriteLine();
  • The Output Window is emptied every time the Output.Clear() method is called.

For more on formatting text, see the articles on escape characters, numeric values to text, composite formatting and substitution parameters, and converting DateTime to different date layouts.

When using the Output Window for ‘debugging’, it often is useful to include the bar time or computer time. To control how times are outputted, these DateTime values needs to be composed with a format string.

DateTime and format strings in C#

DateTime values contain moments in time (like a date), while TimeSpan stores the duration, or amount of time (Albahari & Albahari, 2012; Sempf et al., 2010).

The DateTime struct in C# holds information about a time and a date (Dorman, 2010; Sempf, Sphar, & Davis, 2010). Two types of format strings specify how these values are converted to a string (Dorman, 2010):

  • Standard format strings contain a single character (called the format specifier) that defines a more complete format string;
  • Custom format strings consist out of one or more format specifiers that act as a template to define the exact string representation.

These format strings can be used in two ways (Dorman, 2010): by calling an object’s ToString() method and providing the format string as an argument. Or with composite formatting whereby the format string is provided after a semicolon following the substitution parameter. Both approaches are used in the example.

Format specifiers in C# to convert DateTime to time

The following standard and custom format specifiers convert the time component of DateTime values to a string (Albahari & Albahari, 2012; Dorman, 2010; Microsoft Developer Network [MSDN], n.d. a, n.d. b):

DateTime format string Description Example
Standard format string
"t" Short time pattern. Returns "7:04" when the time is 7:04:33.
"T" Long time pattern. Returns "7:05:45" when the time is 7:05:45.
Custom format string
"h" The hour, using a 12-hour clock from 0 to 11. Returns "3" when the time is 15:10:44.
"hh" The hour, using a 12-hour clock from 00 to 11. Returns "03" when the time is 15:10:44.
"H" The hour, using a 24-hour clock from 0 to 23. Returns "9" when the time is 9:07:14.
"HH" The hour, using a 24-hour clock from 00 to 23. Returns "09" when the time is 9:07:14.
"m" The minute, from 0 through 59. Returns "8" when the time is 14:08:05.
"mm" The minute, from 00 through 59. Returns "08" when the time is 14:08:05.
"s" The second, from 0 to 59. Returns "5" when the time is 14:08:05.
"ss" The second, from 00 to 59. Returns "05" when the time is 14:08:05.
"f", "F" Returns the tenths of a second. "F" only does so when this value is non-zero. Returns "9" when the time is 9:14:49.983.
"ff", "FF" Returns the hundredths of a second. "FF" only does so when this value is non-zero. Returns "98" when the time is 9:14:49.983.
"fff", "FFF" Returns the milliseconds. "FFF" returns nothing when this value is zero. Returns "983" when the time is 9:14:49.983.
"ffff", "FFFF" Returns the ten thousandths of a second. "FFFF" returns an empty string when this value is zero. Returns "9831" when the time is 9:14:49.983153.
"fffff", "FFFFF" Both return the hundred thousandths of a second, but "FFFFF" only does so when this value is non-zero. Returns "98315" when the time is 9:14:49.983153.
"fffffff", "FFFFFF" Both return the ten millionths of a second, but "FFFFFF" returns an empty string when this value is zero. Returns "983153" when the time is 9:14:49.983153.
"t" The first character of the AM/PM designator. Returns "A" when the time is 9:16:48 in the morning.

Returns a blank string when the operating system culture settings use a 24-hour clock.
"tt" The AM/PM designator. Returns "AM" when the time is 9:16:48 in the morning.

Returns a blank string when the operating system is set to a 24-hour clock.
"K" Time zone information. Returns "+02:00" when the operating system is set to the UTC + 2 time zone.
"z" Hours offset from UTC, with no leading zeros. Returns "+2" when the operating system's culture settings are set to the UTC + 2 time zone.
"zz" Hours offset from UTC, with a leading zero for single-digit values. Returns "+02" when the operating system is set to the UTC + 2 time zone.
"zzz" Hours and minutes offset from UTC. Returns "+02:00" when the operating system is set to the UTC + 2 time zone.
":" The time separator. Returns "9:20:27" when the time is 9:20:27 and the "H:m:s" format string is used.
"string", 'string' Literal string delimiter. The enclosed characters are copied to the string unchanged. Returns "The time is: 09:20:27" when the time is 9:20:27 and the "'The time is:' HH:mm:ss" format string is used.
\ The escape character causes the next character to be interpreted as a literal character rather than a custom format specifier. The format string "\t\tH:mm:ss" returns the current time with two preceding tabs.
Other All other characters are copied to the result string unchanged. The "arr H:m" format string prints "arr 9:25" when the time is 9:25.

Any custom format specifier in the string will automatically be converted: a string like "hello" will be printed as "9ello" when the hour is 9. Use the literal string delimiter to prevent this.

See converting DateTime’s dates to string for converting the date part of DateTime to a string.

When only a single custom format specifier is used in the format string, it needs to be preceded by the percent (%) symbol (Dorman, 2010): otherwise, it will either be interpreted as a standard format specifier or throw a FormatException (MSDN, n.d. b).

MultiCharts .NET programming example

The example begins with setting two MultiCharts .NET class attributes:

[UpdateOnEveryTick(false), SameAsSymbol(true)]

UpdateOnEveryTick set to false ensures that the indicator is only calculated on bar close, while setting the SameAsSymbol attribute to true prevents the indicator from making a subchart.

Setting the indicator’s MaxBarsBack in MultiCharts .NET

Next is the StartCalc() override method:

protected override void StartCalc()
{
    ExecInfo.MaxBarsBack = 5;
    Output.Clear();
}

The MaxBarsBack are set programmatically here to 5 by assigning this value to the ExecInfo.MaxBarsBack property. This prevents a script recalculation due to 'Auto-Detect' MaxBarsBack. Otherwise, the Output Window would have been cleared more than once with Output.Clear() (line 16), preventing the output from the indicator from being shown.

Outputting time values formatted in MultiCharts .NET

The last part is the CalcBar() override method, which contains the following if statement:

if (Bars.LastBarOnChart)
{
    Output.WriteLine("Bar time: {0:H:m}, previous bar time: {1}.",
        Bars.Time[0],
        Bars.Time[1].ToString("HH:mm:ss 'on date:' d-M-y"));

    DateTime timeNow = DateTime.Now;
    Output.WriteLine("The current time is: {0:HH:mm:ss.fff}.",
        timeNow);
}

The Bars.LastBarOnChart property returns true when the current bar is the last bar on the chart. In that case the body of the if statement is executed, which consists out of two parts: outputting bar time data and printing the current computer time.

Outputting the time of price bars in MultiCharts .NET

First, the time of the current bar and a historical bar are outputted:

Output.WriteLine("Bar time: {0:H:m}, previous bar time: {1}.",
    Bars.Time[0],
    Bars.Time[1].ToString("HH:mm:ss 'on date:' d-M-y"));

The time of the current bar (Bars.Time[0]) is inserted into the string with a substitution parameter and the "H:m" format string ({0:H:m}).

PS: See formatting DateTime dates to string for more about formatting date output.

The time of the previous bar (Bars.Time[1]) has its format string provided in the ToString() method. This detailed format string contains contains format specifiers for the time (HH:mm:ss), literal string ('on date:'), and date (d-M-y).

This statement generates the following text:

Bar time: 22:58, previous bar time: 22:06:00 on date: 19-9-14.

Outputting the current computer time in MultiCharts .NET

The second part of the if statement is the following:

DateTime timeNow = DateTime.Now;
Output.WriteLine("The current time is: {0:HH:mm:ss.fff}.",
    timeNow);

A DateTime variable (timeNow) is declared here and assigned the value of the current computer time (DateTime.Now).

The Output.WriteLine() method is used to print this variable to the Output Window. In this method a literal string with a substitution parameter (that includes the HH:mm:ss.fff format string) is passed. The output it generates is the following:

The current time is: 10:02:48.079.

Key points

  • Date and time information in C# is held in the DateTime struct;
  • The Bars.Time property in MultiCharts .NET provides access to the DateTime of current and previous bars;
  • The time component from DateTime values can be converted to a string with standard format strings or custom format strings that allow for more flexibility;
  • Format strings can be used with composite formatting and substitution parameters or by providing them as an argument to the ToString() method.
References

Albahari, J. & Albahari, B. (2012). C# 5.0 in a Nutshell: The Definitive Reference (5th edition). Sebastopol, CA: O’Reilly Media.

Dorman, S. (2010). Sams Teach Yourself Visual C# 2010 in 24 Hours. Indianapolis, IN (USA): Sams/Pearson Education.

Microsoft Developer Network [MSDN] (n.d. a). Standard Date and Time Format Strings. Retrieved on September 20, 2014, from http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx

MSDN (n.d. b). Custom Date and Time Format Strings. Retrieved on September 21, 2014, from http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx

MultiCharts (2013). MultiCharts .NET Programming Guide (version 1.0). Retrieved from http://www.multicharts.com/downloads/MultiCharts.NET-ProgrammingGuide-v1.0.pdf

PowerLanguage .NET Help (n.d.). Retrieved on May 16, 2014, from http://www.multicharts.com/downloads/PowerLanguage.NET.chm

Sempf, B., Sphar, C., & Davis, S.R. (2010). C# 2010 All-In-One for Dummies. Hoboken, NJ: John Wiley & Sons.