C# General Date Short Time ("g") Format Specifier

The General Date Short Time ("g") format specifier in C# is a standard DateTime format that combines the short date pattern ("d") and short time pattern ("t"), separated by a space. This format provides a compact representation of both date and time information.

Syntax

Following is the syntax for using the "g" format specifier −

dateTime.ToString("g")
dateTime.ToString("g", CultureInfo)

The format pattern varies based on the current culture or specified culture. It typically displays −

  • Short date − MM/dd/yyyy or dd/MM/yyyy depending on culture

  • Short time − HH:mm or h:mm tt (12-hour with AM/PM) depending on culture

Using "g" Format with Different Cultures

Example

using System;
using System.Globalization;

class Demo {
   static void Main() {
      DateTime dt = new DateTime(2018, 10, 2, 7, 59, 20);
      
      Console.WriteLine("Invariant Culture: " + dt.ToString("g", DateTimeFormatInfo.InvariantInfo));
      Console.WriteLine("US Culture: " + dt.ToString("g", CultureInfo.CreateSpecificCulture("en-US")));
      Console.WriteLine("UK Culture: " + dt.ToString("g", CultureInfo.CreateSpecificCulture("en-GB")));
      Console.WriteLine("German Culture: " + dt.ToString("g", CultureInfo.CreateSpecificCulture("de-DE")));
   }
}

The output of the above code is −

Invariant Culture: 10/02/2018 07:59
US Culture: 10/2/2018 7:59 AM
UK Culture: 02/10/2018 07:59
German Culture: 02.10.2018 07:59

Comparison with Other Format Specifiers

Format Specifier Description Example Output (en-US)
"g" General Date Short Time 10/2/2018 7:59 AM
"G" General Date Long Time 10/2/2018 7:59:20 AM
"d" Short Date 10/2/2018
"t" Short Time 7:59 AM

Current Date and Time Example

Example

using System;
using System.Globalization;

class Program {
   static void Main() {
      DateTime now = DateTime.Now;
      DateTime utcNow = DateTime.UtcNow;
      
      Console.WriteLine("Local Time (g): " + now.ToString("g"));
      Console.WriteLine("UTC Time (g): " + utcNow.ToString("g"));
      Console.WriteLine("With French Culture: " + now.ToString("g", CultureInfo.CreateSpecificCulture("fr-FR")));
   }
}

The output will vary based on when you run the code, but the format will be similar to −

Local Time (g): 12/15/2023 2:30 PM
UTC Time (g): 12/15/2023 9:30 PM
With French Culture: 15/12/2023 14:30

Conclusion

The "g" format specifier provides a concise way to display both date and time information in a culture-specific format. It's ideal for applications that need to showDateTime values in a readable, compact format that adapts to different regional settings automatically.

Updated on: 2026-03-17T07:04:35+05:30

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements