DateTime.ToShortTimeString() Method in C#


The DateTime.ToShortTimeString() method in C# is used to convert the value of the current DateTime object to its equivalent short time string representation.

Syntax

Following is the syntax −

public string ToShortTimeString ();

Example

Let us now see an example to implement the DateTime.ToShortTimeString() method −

using System;
using System.Globalization;
public class Demo {
   public static void Main() {
      DateTime d = DateTime.Now;
      Console.WriteLine("Date = {0}", d);
      Console.WriteLine("Current culture = "+CultureInfo.CurrentCulture.Name);
      var pattern = CultureInfo.CurrentCulture.DateTimeFormat;
      string str = d.ToShortTimeString();
      Console.WriteLine("Short time string = {0}", pattern.ShortTimePattern);
      Console.WriteLine("Short time string representation = {0}", str);
   }
}

Output

This will produce the following output −

Date = 10/16/2019 8:59:23 AM
Current culture = en-US
Short time string = h:mm tt
Short time string representation = 8:59 AM

Example

Let us now see another example to implement the DateTime.ToShortTimeString() method −

using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 11, 11, 7, 11, 25);
      Console.WriteLine("Date = {0}", d);
      string str = d.ToShortTimeString();
      Console.WriteLine("Short time string representation = {0}", str);
   }
}

Output

This will produce the following output −

Date = 11/11/2019 7:11:25 AM
Short time string representation = 7:11 AM

Updated on: 11-Nov-2019

827 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements