C# DateTime format - formatting DateTime in C# (2024)

last modified July 5, 2023

In this article we show how to do formatting of DateTime objects in C#.

C# DateTime

The DateTime value type represents dates and times with valuesranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era)through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.

Format methods

To format DateTime objects, we can useDateTime.ToString, String.Format or interpolatedstring syntax such as $"{now:D}".

C# standard format specifiers

A standard datetime format string uses a single character format specifier todefine the text representation of a DateTime value. For instance, theD format specifier denotes a long date format.

SpecifierMeaningExample
Dlong dateSaturday, March 26, 2022
dshort date3/26/2022
Ffull date longSaturday, March 26, 2022 12:59:46 PM
ffull date shortSaturday, March 26, 2022 12:59 PM
Ggeneral long3/26/2022 12:59:46 PM
ggeneral short3/26/2022 12:59 PM
Uuniversal fullSaturday, March 26, 2022 11:59:46 AM
uuniversal sortable2022-03-26 12:59:46Z
ssortable2022-03-26T12:59:46
Tlong time12:59:46 PM
tshort time12:59 PM
OISO 86012022-03-26T12:59:46.7831825+01:00
RRFC 1123Sat, 26 Mar 2022 12:59:46 GMT
MmonthMarch 26
Yyear monthMarch 2022

The table lists standard datetime format specifiers in C#.

Program.cs

var now = DateTime.Now;Console.WriteLine(now.ToString("D"));Console.WriteLine(now.ToString("d"));Console.WriteLine(now.ToString("F"));Console.WriteLine(now.ToString("f"));Console.WriteLine(now.ToString("G"));Console.WriteLine(now.ToString("g"));Console.WriteLine(now.ToString("U"));Console.WriteLine(now.ToString("u"));Console.WriteLine(now.ToString("s"));Console.WriteLine(now.ToString("T"));Console.WriteLine(now.ToString("t"));Console.WriteLine(now.ToString("O"));Console.WriteLine(now.ToString("R"));Console.WriteLine(now.ToString("M"));Console.WriteLine(now.ToString("Y"));

In the example, we use standard datetime format specifiers in theDateTime.ToString method to print the current datetime.

$ dotnet run Saturday, March 26, 20223/26/2022Saturday, March 26, 2022 1:15:12 PMSaturday, March 26, 2022 1:15 PM3/26/2022 1:15:12 PM3/26/2022 1:15 PMSaturday, March 26, 2022 12:15:12 PM2022-03-26 13:15:12Z2022-03-26T13:15:121:15:12 PM1:15 PM2022-03-26T13:15:12.6729121+01:00Sat, 26 Mar 2022 13:15:12 GMTMarch 26March 2022

Program.cs

var now = DateTime.Now;Console.WriteLine($"{now:D}");Console.WriteLine($"{now:d}");Console.WriteLine($"{now:F}");Console.WriteLine($"{now:f}");Console.WriteLine($"{now:G}");Console.WriteLine($"{now:g}");Console.WriteLine($"{now:U}");Console.WriteLine($"{now:u}");Console.WriteLine($"{now:s}");Console.WriteLine($"{now:T}");Console.WriteLine($"{now:t}");Console.WriteLine($"{now:O}");Console.WriteLine($"{now:R}");Console.WriteLine($"{now:M}");Console.WriteLine($"{now:Y}");

In the example, we use standard datetime format specifiers inside interpolatedstrings to print the current datetime.

C# culture-specific standard format specifiers

We can pass the CultureInfo to the formatting method.

Program.cs

using System.Globalization;var now = DateTime.Now;var ci = CultureInfo.CreateSpecificCulture("sk-SK");CultureInfo.DefaultThreadCurrentCulture = ci;Console.WriteLine(now.ToString("D"));Console.WriteLine(now.ToString("d"));Console.WriteLine(now.ToString("F"));Console.WriteLine(now.ToString("f"));Console.WriteLine(now.ToString("G"));Console.WriteLine(now.ToString("g"));Console.WriteLine(now.ToString("U"));Console.WriteLine(now.ToString("u"));Console.WriteLine(now.ToString("s"));Console.WriteLine(now.ToString("T"));Console.WriteLine(now.ToString("t"));Console.WriteLine(now.ToString("O"));Console.WriteLine(now.ToString("R"));Console.WriteLine(now.ToString("M"));Console.WriteLine(now.ToString("Y"));

In the example, we print the current datetime with the standard datetime formatspecifiers for the Slovak culture.

$ dotnet run sobota 26. marca 202226. 3. 2022sobota 26. marca 2022 13:22:00sobota 26. marca 2022 13:2226. 3. 2022 13:22:0026. 3. 2022 13:22sobota 26. marca 2022 12:22:002022-03-26 13:22:00Z2022-03-26T13:22:0013:22:0013:222022-03-26T13:22:00.4524483+01:00Sat, 26 Mar 2022 13:22:00 GMT26. marcamarec 2022

C# custom datetime format specifiers

Custom datetime format specifiers are additional specifiers that allow usto build our own datetime formats.

SpecifierMeaning
dThe day of the month, from 1 through 31.
ddThe day of the month, from 01 through 31.
dddThe abbreviated name of the day of the week.
ddddThe full name of the day of the week.
fThe tenths of a second in a date and time value.
ffThe hundredths of a second in a date and time value.
fffThe milliseconds in a date and time value.
ffffThe ten thousandths of a second in a date and time value.
fffffThe hundred thousandths of a second in a date and time value..
ffffffThe hundredths of a second in a date and time value.
fffffffThe millionths of a second in a date and time value.
ffffffffThe ten millionths of a second in a date and time value.
g/ggThe period or era.
hThe hour, using a 12-hour clock from 1 to 12.
hhThe hour, using a 12-hour clock from 01 to 12.
HThe hour, using a 24-hour clock from 0 to 23.
HHThe hour, using a 24-hour clock from 00 to 23.
KTime zone information.
mThe minute, from 0 through 59.
mmThe minute, from 00 through 59.
MThe month, from 1 through 12.
MMThe month, from 01 through 12.
MMMThe abbreviated name of the month.
MMMMThe full name of the month.
sThe second, from 0 through 59.
ssThe second, from 00 through 59.
tThe first character of the AM/PM designator.
ttThe AM/PM designator.
yThe year, from 0 to 99.
yyThe year, from 00 to 99.
yyyThe year, with a minimum of three digits.
yyyyThe year as a four-digit number.
yyyyyThe year as a five-digit number.
zHours offset from UTC, with no leading zeros.
zzHours offset from UTC, with a leading zero for a single-digit value.
zzzHours and minutes offset from UTC.

The table shows custom datetime format specifiers in C#.

Program.cs

var now = DateTime.Now;Console.WriteLine(now.ToString("M/d/yy"));Console.WriteLine(now.ToString("MM/dd/yyyy"));Console.WriteLine(now.ToString("yy-MM-dd"));Console.WriteLine(now.ToString("yy-MMM-dd ddd"));Console.WriteLine(now.ToString("yyyy-M-d dddd"));Console.WriteLine(now.ToString("yyyy MMMM dd"));Console.WriteLine(now.ToString("h:mm:ss tt zzz"));Console.WriteLine(now.ToString("HH:m:s tt zzz"));Console.WriteLine(now.ToString("hh:mm:ss t z"));Console.WriteLine(now.ToString("HH:mm:ss tt zz"));

In the example, we build a few custom datetime formats.

$ dotnet run3/26/2203/26/202222-03-2622-Mar-26 Sat2022-3-26 Saturday2022 March 261:44:03 PM +01:0013:44:3 PM +01:0001:44:03 P +113:44:03 PM +01

Parse datetime strings with format specifiers

Both standard and custom DateTime format specifiers can be usedwhen parsing datetime strings into DateTime objects.

Program.cs

using System.Globalization;var ds = "Thu Nov 11, 2021";var dt = DateTime.ParseExact(ds, "ddd MMM dd, yyyy", CultureInfo.CurrentCulture);Console.WriteLine(dt);var ds2 = "10/22/2021";var dt2 = DateTime.ParseExact(ds2, "d", CultureInfo.CurrentCulture);Console.WriteLine(dt2);

In the example, we pass datetime format specifiers to theDateTime.ParseExact method.

$ dotnet run11/11/2021 12:00:00 AM10/22/2021 12:00:00 AM

Source

Custom date and time format strings

In this article we have formatted DateTime objects in C#.

Author

My name is Jan Bodnar and I am a passionate programmer with many years ofprogramming experience. I have been writing programming articles since 2007. Sofar, I have written over 1400 articles and 8 e-books. I have over eight years ofexperience in teaching programming.

List all C# tutorials.

C# DateTime format - formatting DateTime in C# (2024)

FAQs

C# DateTime format - formatting DateTime in C#? ›

If you have to put your DateTime value directly into your query string, you can simply use myDate. ToString("MM/dd/yyyy",CultureInfo. InvariantCulture); .

How to get mm dd yyyy format in C#? ›

If you have to put your DateTime value directly into your query string, you can simply use myDate. ToString("MM/dd/yyyy",CultureInfo. InvariantCulture); .

How to convert DateTime to custom format in C#? ›

You can use the DateTime. ToString(string format) method in C# to convert a DateTime object to a string representation in a custom format. The format parameter is a string that specifies the desired format of the output string.

How to convert string into date format yyyy mm dd in C#? ›

ParseExact() method converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly. string dateInyyyyMMdd = "20220519"; DateTime dateTime; dateTime = DateTime. ParseExact(dateInyyyyMMdd, "yyyyMMdd", CultureInfo.

What is the default format for date time in C#? ›

Sortable date time is a standardized format for representing date and time values as strings, adhering to the ISO 8601 specification. It follows the specific pattern of 'yyyy-MM-ddTHH:mm:ss' (for example, '2023–04–26T10:37:16').

How to set format DateTime in C#? ›

WriteLinenow. ToString(“MMMM d, yyyy”)); // Results in “December 31, 2020” now. ToString(“d-MMM-yy”)); // Results in “31-Dec-20” In the first print statement, the ToString method follows the custom format string “MMMM d, yyyy” to deliver the full month name, day, and year separated by space and comma.

How to change DateTime in C#? ›

In C#, there are several different ways to change a string into a datetime. Nonetheless, a DateTime object can be created from a date and time string in C#. The techniques are: Parse(), ParseExact(), TryParse() and TryParseExact().

How do I convert DateTime to a different format? ›

Using the CONVERT Function to Format Dates and Times in SQL Server
  1. GETDATE(): It returns server datetime in “YYYY-MM-DD HH:mm:ss. ...
  2. GETUTCDATE(): It returns datetime in GMT.
  3. SYSDATETIME(): It returns server's datetime.
  4. SYSDATETIMEOFFSET(): It returns server's datetime with time zone on which SQL Server instance is running.

What is the DateTime format? ›

dd/MM/yyyy — Example: 23/06/2013. yyyy/M/d — Example: 2013/6/23. yyyy-MM-dd — Example: 2013-06-23. yyyyMMddTHH:mmzzz — Example: 20130623T13:22-0500.

How to create a new DateTime in C#? ›

Working with Date and Time in C#
  1. DateTime newDate = new DateTime(year, month, day); DateTime newDate = new DateTime(year, month, day, hour, munite, second);
  2. DateTime currentDateTime = DateTime.Now; //returns current date and time. ...
  3. // Calculate age with TimeSpan struct.
Aug 30, 2020

How to get the format of a date string in C#? ›

ToString("MM-dd-yyyy HH:mm:ss")); In this example, we're using the ToString method with a pattern like "MM-dd-yyyy HH:mm:ss". This pattern instructs C# to display the DateTime as month, day, year, hour, minute, and second, separated by dashes and colons.

How to convert DateTime to string in specific format in C#? ›

To format it using the general date and time format specifier ('G') for a specific culture, call the ToString(IFormatProvider) method. To format it using a specific date and time format specifier and the conventions of a specific culture, call the ToString(String, IFormatProvider) method.

How to parse DateTime in C#? ›

string dateString = "Tue 16 Jun 8:30 AM 2008"; string format = "ddd dd MMM h:mm tt yyyy"; DateTime dateTime = DateTime. ParseExact(dateString, format, CultureInfo. InvariantCulture); Unhandled Exception: System.

How to get DateTime in 24 hour format in C#? ›

DateTime date = DateTime. ParseExact(strDate, "dd/MM/YYYY HH:mm:ss", CultureInfo. InvariantCulture);

How to create DateTime C# with specific date? ›

DateTime DT = new DateTime(2019,05,09,9,15,0);// this will initialize variable with a specific date(09/05/2019) and time(9:15:00). Note: The (year, month, day, hour, minute, second) format is followed.

How to set date format dd MM yyyy in ASP.NET C#? ›

C# Code
  1. using System.Globalization;
  2. public partial class DateConversion: System.Web.UI.Page.
  3. {
  4. #region How to convert dd / mm / yyyy into dd - mm - yyyy.
  5. protected void btnConvert_Click(object sender, EventArgs e)
  6. {
  7. DateTime dt = DateTime.ParseExact(txtDate.Text, "dd/MM/yy", CultureInfo.InvariantCulture);
Jun 18, 2016

How to convert date to specific format in C#? ›

dateString = "Sun 15 Jun 2008 8:30 AM -06:00"; format = "ddd dd MMM yyyy h:mm tt zzz"; try { result = DateTime. ParseExact(dateString, format, provider); Console. WriteLine("{0} converts to {1}.", dateString, result. ToString()); } catch (FormatException) { Console.

How to format string in C#? ›

Example 1: C# String Format()

string strFormat = String. Format("There are {0} apples.", number); Here, "There are {0} apples." is a format string.

How to get date in different format in C#? ›

In C#, you can get a date and string from a DateTime object into different formats using the ToString() method. Specify the format as a string parameter in the ToString() method to get the date string in the required format. The following example demonstrates getting the date and time string in different formats.

Top Articles
Carbs in Trader Joe's Gluten Free Bagels
What Is Paella and How Do You Make It At Home?
Jps Occupational Health Clinic
Peralta's Mexican Restaurant Grand Saline Menu
Gma Deals And Steals December 5 2022
New Zero Turn Mowers For Sale Near Me
Craigslist Free En Dallas Tx
15:30 Est
One Hour Rosemary Focaccia Bread
24 Hour Lock Up Knoxville Tn
Www.1Tamilmv.con
Thomas Funeral Home Sparta Nc
Magic Seaweed Pleasure Point
Vonage Support Squad.screenconnect.com
Teen Movie Night at Kimball Junction (Percy Jackson and the Lightning Thief)
Pritzker Sdn 2023
Spanish Flower Names: 150+ Flowers in Spanish
Www.burlingtonfreepress.com Obituaries
So sehen die 130 neuen Doppelstockzüge fürs Land aus
15:30 Est
Friend Offers To Pay For Friend’s B-Day Dinner, Refuses When They See Where He Chose
Cavender’s 50th Anniversary: How the Cavender Family Built — and Continues to Grow — a Western Wear Empire Using Common Sense values
Cn/As Archives
Appraisalport Com Dashboard /# Orders
Pirates Point Lake Of The Ozarks
Jen Chapin Gossip Bakery
Reptile Expo Spokane
Daves Supermarket Weekly Ad
Cars & Trucks By Owner
Worldfree4U In
June Month Weather
Tri-State Dog Racing Results
Build a Free Website | VistaPrint
Dfw Rainfall Last 72 Hours
Babymukki
Odawa Hypixel
Diablo 3 Metascore
Expend4bles | Rotten Tomatoes
Arcane Stitch Divinity 2
NUROFEN Junior Fieber-u.Schmerzsaft Oran.40 mg/ml - Beipackzettel
Lmsyduycdmt
Pawn Shops In Sylva Nc
Fitbod Lifetime
Nusl Symplicity Login
Ucla Football 247
Lifetime Benefits Login
The Complete Guide to Chicago O'Hare International Airport (ORD)
Uk Pharmacy Turfland
Cargurus Button Girl
Walb Game Forecast
Craigslist For Puppies For Sale
Never Would Have Made It Movie 123Movies
Latest Posts
Article information

Author: Carlyn Walter

Last Updated:

Views: 6788

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Carlyn Walter

Birthday: 1996-01-03

Address: Suite 452 40815 Denyse Extensions, Sengermouth, OR 42374

Phone: +8501809515404

Job: Manufacturing Technician

Hobby: Table tennis, Archery, Vacation, Metal detecting, Yo-yoing, Crocheting, Creative writing

Introduction: My name is Carlyn Walter, I am a lively, glamorous, healthy, clean, powerful, calm, combative person who loves writing and wants to share my knowledge and understanding with you.