- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
How can i change a date string format
I'm returning from Facebook Graph a friend birthday in MM/DD/YYY format. I need to show it in DD/MM/YYY, cause it's the brazil date format. I'am returnin a M/D string. I cant change the datetime format. How can I only display D/M for the user without changing datetime? Only manipulating the returning string?
- 1 Did you try anything? – Soner Gönül Jun 28, 2013 at 14:15
- try yourdatevalue.toString("D/M"); – Marco Jun 28, 2013 at 14:16
- 1 Please refer to the MSDN documentation; msdn.microsoft.com/en-us/library/8kb3ddd4.aspx – valverij Jun 28, 2013 at 14:17
- For example. My friend's birthday is 02/01 (February 1) i need to show the user (01/02 - February 1 in pt-br format) – Gabriel Carvalho Jun 28, 2013 at 14:17
- Error: Cannot convert from 'string' to 'System.IFormatProvider' – Gabriel Carvalho Jun 28, 2013 at 14:20
3 Answers 3
The error that you're receiving tells me that your birthday variable is a string . To format it, you can first convert it to a DateTime (it's probably the simplest way).
Like I said in the comments above, you can check out more about formatting dates here:
- Custom Date and Time Format Strings
Depending on the format just take your date to string.
and so on. please refer to http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx for further information
If you don't want to input the format manually, you can do this instead:
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged c# asp.net datetime or ask your own question .
- The Overflow Blog
- Five Stack Exchange sites turned ten years old this quarter!
- “Move fast and break things” doesn’t apply to other people’s savings (Ep. 544)
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Turning possible a gigantic rock in the sky (sci-fi and magic)
- Concrete base for parcel box
- Is it inappropriate to tell my boss that "baby talk" is unprofessional?
- How did theorists determine that the atmosphere attenuates enough to support unpowered orbits?
- Is it possible to save Geometry Nodes modifier?
- Does oven polenta actually work?
- What laws would Jesus be breaking if he were to turn water into wine today?
- Full round spell and being attacked
- Max-heap implementation in C
- Should the sticker on top of a HDD be peeled?
- Buffered polygon is not as expected QGIS
- Should I ask why they are interested in me in an interview for a faculty position?
- Pixel 5 vibrates once when turned face down
- Has anyone measured what a high-impedance pin looks like?
- How deep underground could a city plausably be?
- Pathfinder 2e help with a kobold draconic instinct barbarian build
- "Als" in the sense of time at the same time as "als" in the sense of "than"
- Under what circumstances is NYS Refund taxable?
- How to make a better visualization for two close curves?
- Which type of license doesn't require attribution in GitHub projects?
- Is this food box safe for electronics?
- Should certificate validity be policed on open TLS connections?
- Aligning polynomial expansion
- Create number 985 using 1 3 5 7 9
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Standard date and time format strings
- 29 minutes to read
- 22 contributors
A standard date and time format string uses a single character as the format specifier to define the text representation of a DateTime or a DateTimeOffset value. Any date and time format string that contains more than one character, including white space, is interpreted as a custom date and time format string . A standard or custom format string can be used in two ways:
To define the string that results from a formatting operation.
To define the text representation of a date and time value that can be converted to a DateTime or DateTimeOffset value by a parsing operation.
You can download the Formatting Utility , a .NET Windows Forms application that lets you apply format strings to either numeric or date and time values and display the result string. Source code is available for C# and Visual Basic .
Some of the C# examples in this article run in the Try.NET inline code runner and playground. Select the Run button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.
The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. This may affect the behavior and the output of examples that illustrate the DateTime , DateTimeOffset , and TimeZoneInfo types and their members.
Table of format specifiers
The following table describes the standard date and time format specifiers. Unless otherwise noted, a particular standard date and time format specifier produces an identical string representation regardless of whether it is used with a DateTime or a DateTimeOffset value. See Control Panel Settings and DateTimeFormatInfo Properties for additional information about using standard date and time format strings.
How standard format strings work
In a formatting operation, a standard format string is simply an alias for a custom format string. The advantage of using an alias to refer to a custom format string is that, although the alias remains invariant, the custom format string itself can vary. This is important because the string representations of date and time values typically vary by culture. For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".
If a standard format string in a formatting operation maps to a particular culture's custom format string, your application can define the specific culture whose custom format strings are used in one of these ways:
You can use the default (or current) culture. The following example displays a date using the current culture's short date format. In this case, the current culture is en-US.
You can pass a CultureInfo object representing the culture whose formatting is to be used to a method that has an IFormatProvider parameter. The following example displays a date using the short date format of the pt-BR culture.
You can pass a DateTimeFormatInfo object that provides formatting information to a method that has an IFormatProvider parameter. The following example displays a date using the short date format from a DateTimeFormatInfo object for the hr-HR culture.
For information about customizing the patterns or strings used in formatting date and time values, see the NumberFormatInfo class topic.
In some cases, the standard format string serves as a convenient abbreviation for a longer custom format string that is invariant. Four standard format strings fall into this category: "O" (or "o"), "R" (or "r"), "s", and "u". These strings correspond to custom format strings defined by the invariant culture. They produce string representations of date and time values that are intended to be identical across cultures. The following table provides information on these four standard date and time format strings.
Standard format strings can also be used in parsing operations with the DateTime.ParseExact or DateTimeOffset.ParseExact methods, which require an input string to exactly conform to a particular pattern for the parse operation to succeed. Many standard format strings map to multiple custom format strings, so a date and time value can be represented in a variety of formats and the parse operation will still succeed. You can determine the custom format string or strings that correspond to a standard format string by calling the DateTimeFormatInfo.GetAllDateTimePatterns(Char) method. The following example displays the custom format strings that map to the "d" (short date pattern) standard format string.
The following sections describe the standard format specifiers for DateTime and DateTimeOffset values.
Date formats
This group includes the following formats:
The short date ("d") format specifier
The long date ("d") format specifier.
The "d" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.ShortDatePattern property. For example, the custom format string that is returned by the ShortDatePattern property of the invariant culture is "MM/dd/yyyy".
The following table lists the DateTimeFormatInfo object properties that control the formatting of the returned string.
The following example uses the "d" format specifier to display a date and time value.
Back to table
The "D" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.LongDatePattern property. For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy".
The following table lists the properties of the DateTimeFormatInfo object that control the formatting of the returned string.
The following example uses the "D" format specifier to display a date and time value.
Date and time formats
The full date short time ("f") format specifier, the full date long time ("f") format specifier, the general date short time ("g") format specifier, the general date long time ("g") format specifier, the round-trip ("o", "o") format specifier, the rfc1123 ("r", "r") format specifier, the sortable ("s") format specifier, the universal sortable ("u") format specifier, the universal full ("u") format specifier.
The "f" standard format specifier represents a combination of the long date ("D") and short time ("t") patterns, separated by a space.
The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier returned by the DateTimeFormatInfo.LongDatePattern and DateTimeFormatInfo.ShortTimePattern properties of some cultures may not make use of all properties.
The following example uses the "f" format specifier to display a date and time value.
The "F" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.FullDateTimePattern property. For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy HH:mm:ss".
The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by the FullDateTimePattern property of some cultures may not make use of all properties.
The following example uses the "F" format specifier to display a date and time value.
The "g" standard format specifier represents a combination of the short date ("d") and short time ("t") patterns, separated by a space.
The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by the DateTimeFormatInfo.ShortDatePattern and DateTimeFormatInfo.ShortTimePattern properties of some cultures may not make use of all properties.
The following example uses the "g" format specifier to display a date and time value.
The "G" standard format specifier represents a combination of the short date ("d") and long time ("T") patterns, separated by a space.
The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by the DateTimeFormatInfo.ShortDatePattern and DateTimeFormatInfo.LongTimePattern properties of some cultures may not make use of all properties.
The following example uses the "G" format specifier to display a date and time value.
The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind .
The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string.
The "O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values:
The time zone component of DateTimeKind.Local date and time values is an offset from UTC (for example, +01:00, -07:00). All DateTimeOffset values are also represented in this format.
The time zone component of DateTimeKind.Utc date and time values uses "Z" (which stands for zero offset) to represent UTC.
DateTimeKind.Unspecified date and time values have no time zone information.
Because the "O" or "o" standard format specifier conforms to an international standard, the formatting or parsing operation that uses the specifier always uses the invariant culture and the Gregorian calendar.
Strings that are passed to the Parse , TryParse , ParseExact , and TryParseExact methods of DateTime and DateTimeOffset can be parsed by using the "O" or "o" format specifier if they are in one of these formats. In the case of DateTime objects, the parsing overload that you call should also include a styles parameter with a value of DateTimeStyles.RoundtripKind . Note that if you call a parsing method with the custom format string that corresponds to the "O" or "o" format specifier, you won't get the same results as "O" or "o". This is because parsing methods that use a custom format string can't parse the string representation of date and time values that lack a time zone component or use "Z" to indicate UTC.
The following example uses the "o" format specifier to display a series of DateTime values and a DateTimeOffset value on a system in the U.S. Pacific Time zone.
The following example uses the "o" format specifier to create a formatted string, and then restores the original date and time value by calling a date and time Parse method.
The "R" or "r" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.RFC1123Pattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.
The result string is affected by the following properties of the DateTimeFormatInfo object returned by the DateTimeFormatInfo.InvariantInfo property that represents the invariant culture.
Although the RFC 1123 standard expresses a time as Coordinated Universal Time (UTC), the formatting operation does not modify the value of the DateTime object that is being formatted. Therefore, you must convert the DateTime value to UTC by calling the DateTime.ToUniversalTime method before you perform the formatting operation. In contrast, DateTimeOffset values perform this conversion automatically; there is no need to call the DateTimeOffset.ToUniversalTime method before the formatting operation.
The following example uses the "r" format specifier to display a DateTime and a DateTimeOffset value on a system in the U.S. Pacific Time zone.
The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".
The purpose of the "s" format specifier is to produce result strings that sort consistently in ascending or descending order based on date and time values. As a result, although the "s" standard format specifier represents a date and time value in a consistent format, the formatting operation does not modify the value of the date and time object that is being formatted to reflect its DateTime.Kind property or its DateTimeOffset.Offset value. For example, the result strings produced by formatting the date and time values 2014-11-15T18:32:17+00:00 and 2014-11-15T18:32:17+08:00 are identical.
When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.
The following example uses the "s" format specifier to display a DateTime and a DateTimeOffset value on a system in the U.S. Pacific Time zone.
The "u" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.UniversalSortableDateTimePattern property. The pattern reflects a defined standard, and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'". When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.
Although the result string should express a time as Coordinated Universal Time (UTC), no conversion of the original DateTime value is performed during the formatting operation. Therefore, you must convert a DateTime value to UTC by calling the DateTime.ToUniversalTime method before formatting it. In contrast, DateTimeOffset values perform this conversion automatically; there is no need to call the DateTimeOffset.ToUniversalTime method before the formatting operation.
The following example uses the "u" format specifier to display a date and time value.
The "U" standard format specifier represents a custom date and time format string that is defined by a specified culture's DateTimeFormatInfo.FullDateTimePattern property. The pattern is the same as the "F" pattern. However, the DateTime value is automatically converted to UTC before it is formatted.
The "U" format specifier is not supported by the DateTimeOffset type and throws a FormatException if it is used to format a DateTimeOffset value.
The following example uses the "U" format specifier to display a date and time value.
Time formats
The short time ("t") format specifier, the long time ("t") format specifier.
The "t" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.ShortTimePattern property. For example, the custom format string for the invariant culture is "HH:mm".
The result string is affected by the formatting information of a specific DateTimeFormatInfo object. The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by the DateTimeFormatInfo.ShortTimePattern property of some cultures may not make use of all properties.
The following example uses the "t" format specifier to display a date and time value.
The "T" standard format specifier represents a custom date and time format string that is defined by a specific culture's DateTimeFormatInfo.LongTimePattern property. For example, the custom format string for the invariant culture is "HH:mm:ss".
The following table lists the DateTimeFormatInfo object properties that may control the formatting of the returned string. The custom format specifier that is returned by the DateTimeFormatInfo.LongTimePattern property of some cultures may not make use of all properties.
The following example uses the "T" format specifier to display a date and time value.
Partial date formats
The month ("m", "m") format specifier, the year month ("y", "y") format specifier.
The "M" or "m" standard format specifier represents a custom date and time format string that is defined by the current DateTimeFormatInfo.MonthDayPattern property. For example, the custom format string for the invariant culture is "MMMM dd".
The following example uses the "m" format specifier to display a date and time value.
The "Y" or "y" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.YearMonthPattern property of a specified culture. For example, the custom format string for the invariant culture is "yyyy MMMM".
The following example uses the "y" format specifier to display a date and time value.
Control Panel settings
In Windows, the settings in the Regional and Language Options item in Control Panel influence the result string produced by a formatting operation. These settings are used to initialize the DateTimeFormatInfo object associated with the current culture, which provides values used to govern formatting. Computers that use different settings generate different result strings.
In addition, if you use the CultureInfo(String) constructor to instantiate a new CultureInfo object that represents the same culture as the current system culture, any customizations established by the Regional and Language Options item in Control Panel will be applied to the new CultureInfo object. You can use the CultureInfo(String, Boolean) constructor to create a CultureInfo object that does not reflect a system's customizations.
DateTimeFormatInfo properties
Formatting is influenced by properties of the current DateTimeFormatInfo object, which is provided implicitly by the current culture or explicitly by the IFormatProvider parameter of the method that invokes formatting. For the IFormatProvider parameter, your application should specify a CultureInfo object, which represents a culture, or a DateTimeFormatInfo object, which represents a particular culture's date and time formatting conventions. Many of the standard date and time format specifiers are aliases for formatting patterns defined by properties of the current DateTimeFormatInfo object. Your application can change the result produced by some standard date and time format specifiers by changing the corresponding date and time format patterns of the corresponding DateTimeFormatInfo property.
- System.DateTime
- System.DateTimeOffset
- Formatting Types
- Custom Date and Time Format Strings
- Sample: .NET Core WinForms Formatting Utility (C#)
- Sample: .NET Core WinForms Formatting Utility (Visual Basic)
Submit and view feedback for
Additional resources

String Format for DateTime [C#]
This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.
Custom DateTime Formatting
There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator .
Here are some examples of custom date and time formatting:
Standard DateTime Formatting
In DateTimeFormatInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeFormatInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
- [C#] String Format for Double – format float numbers
- [C#] String Format for Int – format (align) integer numbers
- [C#] IFormatProvider for Numbers – parse float numbers with IFormatProvider
- [C#] Custom IFormatProvider – string formatting with custom IFormatProvider
- [C#] Align String with Spaces – how to align text to the right or left
- [C#] Indent String with Spaces – how to indent text with repeated spaces
- Custom Date and Time Format Strings – MSDN – custom date-time formatting
- Standard Date and Time Format Strings – MSDN – standard date-time formatting
- DateTimeFormatInfo – MSDN – date-time patterns for specific cultures
- String.Format – MSDN – method to format strings
- [C#] List Examples – illustrative examples of all List<T> methods
- [C#] Foreach Examples – how foreach and IEnumerable works debuggable online
- [C#] Switch Examples – switch statement examples debuggable online
- [C#] Using Statement Examples – using statement and IDisposable debuggable online
By Jan Slama , 25-Mar-2008

- Blazor WASM 🔥
- ASP.NET Core Series
- GraphQL ASP.NET Core
- ASP.NET Core MVC Series
- Testing ASP.NET Core Applications
- EF Core Series
- HttpClient with ASP.NET Core
- Azure with ASP.NET Core
- ASP.NET Core Identity Series
- IdentityServer4, OAuth, OIDC Series
- Angular with ASP.NET Core Identity
- Blazor WebAssembly
- .NET Collections
- SOLID Principles in C#
- ASP.NET Core Web API Best Practices
- Top REST API Best Practices
- Angular Development Best Practices
- 10 Things You Should Avoid in Your ASP.NET Core Controllers
- C# Back to Basics
- C# Intermediate
- Design Patterns in C#
- Sorting Algorithms in C#
- Docker Series
- Angular Series
- Angular Material Series
- HTTP Series
- .NET/C# Author
- .NET/C# Editor
- Leave Us a Review
- Code Maze Reviews
Select Page
DateTime Format In C#
Posted by Code Maze | Feb 28, 2022 | 2

In this article, we are going to learn how to work with DateTime format strings in C#. We can use format specifiers in C# to get string representations of DateTime values or to define the input string in a parse operation. The DateTime and DateTimeOffset classes in C# are responsible for handling date and time values. Therefore, both classes contain various methods that can work with standard and custom format specifiers.
Let’s start.
Standard DateTime Formatting in C#
Standard date and time format specifiers consist always of a single character that defines a particular string representation of a DateTime or DateTimeOffset value:
This formatting operation uses the default or current culture. The output from our example corresponds to US English.
Now, let’s see the complete list of standard format specifiers that formatting operations in C# support:
Standard Formats and Culture
Standard format specifiers are useful because the same format specifier will throw different representations of a date and time value depending on the culture we use in the operation:
Here, we pass a culture info specification as the value of the IFormatProvider parameter of the ToString method.
We use the US English date format that corresponds to the MM/dd/yyyy custom format string. Then the Spanish culture setting with the dd/MM/yyyy format representation. And lastly, we use the Japanese standard short date format – yyyy/MM/dd .
As an alternative to CultureInfo , we can use a more customizable DateTimeFormatInfo object:
First, we access the DateTimeFormat property of DateTimeFormatInfo type associated with the American English culture and store it in the formatInfo variable. After that, we customize it by setting the date separator to the hyphen character - instead of the culture default forward slash / . Finally, we use DateTimeFormat along with the short date standard format specifier to print a DateTime value to the console.
In the same way, we can use format providers when parsing string values to DateTime using ParseExact and TryParseExact methods:
Here we use the short date standard format specifier d to parse a string literal. Additionally, we specify an American English culture information. With this, our app will use the MM/dd/yyyy format to try to convert the string into the DateTime value.
Date Format Specifiers
We can use the short date format specifier d to show the short date value in combination with a specific culture that we use:
Console.WriteLine(datetime.ToString("d", CultureInfo.CreateSpecificCulture("en-US"))); // 8/24/2017
With the long date format specifier D we can show the long date format:
Console.WriteLine(datetime.ToString("D", CultureInfo.CreateSpecificCulture("en-US"))); // Thursday, August 24, 2017
We can find an additional implementation of Spanish and Japanese cultures in our source code .
Date and Time Format Specifiers
The full date short time format specifier f is a combination of the long date and short time standard formats:
Console.WriteLine(datetime.ToString("f", CultureInfo.CreateSpecificCulture("en-US")));
The output:
Thursday, August 24, 2017 2:35 PM
With the full date long time format specifier F we can show a combination of the long date and long time standard formats:
Console.WriteLine(datetime.ToString("F", CultureInfo.CreateSpecificCulture("en-US")));
And this is the output:
Thursday, August 24, 2017 2:35:00 PM
We can use the general date short time format specifier g to show a combination of short date and short time patterns:
Console.WriteLine(datetime.ToString("g", CultureInfo.CreateSpecificCulture("en-US"))); // 8/24/2017 2:35 PM
The general date long time format specifier G shows a value that combines the short date pattern and the long time patterns:
Console.WriteLine(datetime.ToString("G", CultureInfo.CreateSpecificCulture("en-US"))); // 8/24/2017 2:35:00 PM
With the round-trip format specifier O or o we can show an ISO 8601 representation. This formatting preserves time zone information:
Here, we print a formatted version of a DateTime value. This DateTime value has zero offset since its kind is UTC. Then, we do the same with a DateTimeOffset value.
Note that our UTC DateTime representation shows the fact that it has zero offset by adding a capital Z to the end of the string.
The DateTimeOffset value represents the offset time value at the end. In this case, +02:00 means 2 hours over UTC.
The RFC1123 Format Specifier
With the format specifier R or r we can show a value that follows the RFC1123 standard.
RFC1123 always represents the time in UTC format. However, for DateTime values, we will need to make sure that we are providing a UTC value to the formatting operation. The easier way to do that is by calling the DateTime.ToUniversalTime() method.
For DateTimeOffset values, it’s easier since the conversion to universal time is performed automatically:
Sortable and Full Format Specifiers
We can use the sortable format specifier s to show a value that complies with the ISO 8601 standard and, as the name suggests, sorts correctly according to their date and time values. This format doesn’t represent time offset information:
Console.WriteLine(datetime.ToString("s")); // 2017-08-24T14:35:00
With the universal sortable format specifier u we can generate a value that complies with the ISO 8601 standard and produces sortable string representation. This format only works with universal date and time values. Therefore, we need to make sure we are using a UTC value, usually, by calling DateTime.ToUniversalTime() :
Console.WriteLine(datetime.ToUniversalTime().ToString("u")); // 2017-08-24 14:35:00Z
Note that the zero offset marker Z at the end of the string will appear regardless of the DateTime.Kind property of the value used. That’s why it is on us to explicitly convert the value to UTC.
In contrast, for DateTimeOffset values, this is done automatically.
Lastly, using the universal full format specifier U we can produce a value that will be identical to the full date and time pattern described before. However, the difference is that the DateTime value used is automatically converted to UTC before applying the format operation.
Note that the universal full format specifier only works with DateTime values. Any attempt to use the U standard format on a DateTimeOffset value with throw a FormatException .
Let’s see how to format a DateTime value using this specifier:
Here, we create a DateTime value specifying a DateTime.Kind UTC even though it is not strictly necessary:
Time Format Specifiers
With the short time format specifier t we can represent a short time value using different cultures:
Console.WriteLine(datetime.ToString("t", CultureInfo.CreateSpecificCulture("en-US"))); // 2:35 PM
Alternatively, we can use the long time format specifier T to represent a short time value that changes depending on the culture we use:
Console.WriteLine(datetime.ToString("T", CultureInfo.CreateSpecificCulture("en-US"))); // 2:35:00 PM
We can find additional implementation examples for different cultures in our source code .
Custom DateTime Format in C#
Formatting operations consider a custom format string any format string longer than a single character.
Both DateTime and DateTimeOffset support the use of custom format strings for string representation and parse operations:
Console.WriteLine("{0:MM/dd/yy H:mm:ss}", datetime); // 08/24/17 14:35:00
Here, we use a method that supports composite formatting and a custom format string to come up with a date and time string representation.
Any formatting or parsing operation always interprets single character format strings as standard format specifiers. Then, if the character doesn’t match any of the supported standard formats a FormatException will be thrown.
In case we want to use a single character custom format string like, for example, y for the one-digit year, we just have to precede it either with a space or a % symbol:
We see how the format string "%d" is interpreted as the custom format specifier for days. After that, we prepend a space before the character y to avoid it being interpreted as a standard format specifier.
The following table contains the complete list of custom format specifiers supported by formatting operations in C#:
Day Format Specifiers
The d specifier shows the day of the month from 1 to 31 while dd shows the day of the month from 01 to 31 with a leading zero for the single-digit days:
We can use the ddd specifier to show the localized abbreviated name of the weekday while dddd shows the full localized weekday name:
Month Format Specifier
The M specifier shows the month from 1 to 12 while with the MM specifier we can show the month from 01 to 12 with a leading zero for the single-digit months:
If we use the MMM specifier, we can show the localized abbreviated month name while MMMM shows the full localized month name:

Year Format Specifier
We can use the y , yy , yyy and yyyy specifiers to represent the year with one to four digits:
Hour Format Specifier
With the h specifier, we can show the hour of the day from 1 to 12 using all relevant digits. If we use the hh specifier, we will get the hour of the day from 01 to 12 with a leading zero for the single-digit hour:
Console.WriteLine(datetime.ToString("hh", CultureInfo.CreateSpecificCulture("en-US"))); // 10
Similarly, if we use the H specifier we can show the hour of the day from 1 to 23 using all relevant digits while the HH specifier shows the hour of the day from 01 to 23 with a leading zero for the single-digit hour:
Console.WriteLine(datetime.ToString("HH", CultureInfo.CreateSpecificCulture("en-US"))); // 22
Minute Format Specifier
We can use the m specifier to show the minute of the hour from 1 to 59 using all relevant digits. Also, with the mm specifier we can show the minute of the hour from 01 to 59 with a leading zero for the single-digit hour:
Console.WriteLine(datetime.ToString("mm", CultureInfo.CreateSpecificCulture("en-US"))); // 35
Seconds Format Specifier
If we use the s specifier we can show the seconds of the minute from 1 to 59 using all relevant digits while the ss specifier shows the seconds of the minute from 01 to 59 with a leading zero for the single-digit hour:
Console.WriteLine(datetime.ToString("ss", CultureInfo.CreateSpecificCulture("en-US"))); // 15
Seconds Fraction specifier
The f specifier shows the seconds fraction. We can use up to seven f characters smaller fractions of a second:
Alternatively, with the F custom format specifier we can obtain the second fractions but, this time, only relevant non-zero digits will be shown. We can use up to seven F characters to increase precision up to ten-millionth of a second:
Meridiem DateTime Format Specifier in C#
The t and tt custom format specifiers represent the AM/PM label in time expression. Note that t will only show the label’s first letter.
We will typically use the meridiem designator in combination with the h or hh custom hour specifier since, otherwise, times that are twelve hours apart would be indistinguishable:
Time Zone Format Specifier
We can use the K custom format specifier to show the time zone information included in date and time values. For DateTime values this specifier depends on value’s Kind property:
Here, we see how the K format string represents the DateTime object time zone with local kind as an offset over the UTC time +02:00. Right after that, the value with UTC kind generates a time zone representation of the UTC time Z .
For DateTimeOffset objects, the internal offset value is used:
We can see how, in this case, the formatting operation for the UTC time (the time with zero offset) shows the numeric value of the offset +00:00 instead of the Z designator.
Offset DateTime Format Specifier in C#
With the z , zz , zzz format specifiers, we can represent the signed time offset.
For DateTime values, the Kind property is not taken into consideration. It just uses the time zone of the operative system clock. Generally speaking, there are very few scenarios in which this is useful.
For DateTimeOffset values, these format specifiers use the internal offset information:
Era Format Specifier
Any of the g and gg format specifiers will show the era, for instance, "AD" , in our DateTime string representation.
The era representation may vary for different cultures:
Console.WriteLine(datetime.ToString("%g", CultureInfo.CreateSpecificCulture("en-US"))); // AD
Time Separator Specifiers
The custom format specifier : outputs the time separator defined by the chosen culture. Standard time formats place the time separator in-between hours, minutes, and seconds values:
First, we store the DateTimeFormatInfo associated to the American English culture in the formatInfo local variable. After that, we set the default time separator for that DateTimeFormatInfo to semicolon ; . Finally, we use that format information to obtain the string representation of a DateTime value using the custom format string HH:mm:ss .
Date Separator Specifiers
The custom format specifier / outputs the date separator defined by the chosen culture. Standard date formats place the date separator in-between day, month, and year values:
First, we store the DateTimeFormatInfo associated with the American English culture in the formatInfo local variable. After that, we set the default date separator for that DateTimeFormatInfo to hyphens - . Finally, we use that format information to obtain the string representation of a DateTime value using the custom format string dd/MM/yyyy .
Character Literals in DateTime Format in C#
All the aforementioned custom format specifiers characters in addition to the symbols : , \ , / , ' and " are always interpreted as formatting or special characters. If we include any other character in a format string, C# will treat it as literal and will not modify it in the resulting string:
The output shows the unchanged EST characters:
24/08/2017 04:22:35 EST
Additionally, parsing operations using a format string with literal characters require those characters to appear in the input string.
We can force any character to be interpreted as a literal character either by using the escape character \\ or by surrounding the literal string with quotation marks or apostrophes:
Here, we use two equivalent format strings that contain the literal string gmt . Since these characters are, also, custom format specifiers, we use the escape character in the format string to force them into literal characters. Then, in the second operation, we enclose the entire literal string in apostrophes:
In this article, we’ve learned about the DateTime format in C# and how formatting and parsing operations use different formats. We’ve seen how standard date and time format strings always consist of a single character that maps to a culture-defined custom format string. Then, we learned about every standard format specifier available.
After that, we went through all the custom format specifiers that allow for fully customized formatting.
To wrap things up, we’ve learned how to override the default date and time separator characters and how to use character literals in our format strings.
Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices .

- An Interview Question
- TECHNOLOGIES
- INTERVIEW PREP

DateTime Format In C#

- Feb 09, 2023
Syntax of C# DateTime Format. This blog describes how to format DateTime in C# with code sample.
C# DateTime Format
Date and Time in C# are handled by DateTime class in C# which provides properties and methods to format dates in different datetime formats. This article blog explains how to work with date and time format in C#.
The following table describes various C# DateTime formats and their results. Here we see all the patterns of the C# DateTime, format, and results.
- d -> Represents the day of the month as a number from 1 through 31.
- dd -> Represents the day of the month as a number from 01 through 31.
- ddd -> Represents the abbreviated name of the day (Mon, Tues, Wed, etc).
- dddd -> Represents the full name of the day (Monday, Tuesday, etc).
- h -> 12-hour clock hour (e.g. 4).
- hh -> 12-hour clock, with a leading 0 (e.g. 06)
- H -> 24-hour clock hour (e.g. 15)
- HH -> 24-hour clock hour, with a leading 0 (e.g. 22)
- m -> Minutes
- mm -> Minutes with a leading zero
- M -> Month number(eg.3)
- MM -> Month number with leading zero(eg.04)
- MMM -> Abbreviated Month Name (e.g. Dec)
- MMMM -> Full month name (e.g. December)
- s -> Seconds
- ss -> Seconds with leading zero
- t -> Abbreviated AM / PM (e.g. A or P)
- tt -> AM / PM (e.g. AM or PM
- y -> Year, no leading zero (e.g. 2015 would be 15)
- yy -> Year, leading zero (e.g. 2015 would be 015)
- yyy -> Year, (e.g. 2015)
- yyyy -> Year, (e.g. 2015)
- K -> Represents the time zone information of a date and time value (e.g. +05:00)
- z -> With DateTime values represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
- zz -> As z, but with leading zero (e.g. +06)
- zzz -> With DateTime values represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. (e.g. +06:00)
- f -> Represents the most significant digit of the seconds' fraction; that is, it represents the tenths of a second in a date and time value.
- ff -> Represents the two most significant digits of the seconds' fraction in date and time
- fff -> Represents the three most significant digits of the seconds' fraction; that is, it represents the milliseconds in a date and time value.
- ffff -> Represents the four most significant digits of the seconds' fraction; that is, it represents the ten-thousandths of a second in a date and time value. While it is possible to display the ten-thousandths of a second component of a time value, that value may not be meaningful.
- fffff -> Represents the five most significant digits of the seconds' fraction; that is, it represents the hundred-thousandths of a second in a date and time value.
- ffffff -> Represents the six most significant digits of the seconds' fraction; that is, it represents the millionths of a second in a date and time value.
- fffffff -> Represents the seven most significant digits of the second's fraction; that is, it represents the ten-millionths of a second in a date and time value.
Here is a complete C# code sample that uses these formats.
Above code sample generates the following output.

Learn More on DateTime
Here is a detailed tutorial on DateTime and formatting: Working with DateTime In C#
Learn about DateTime Class in C#
Calculate Date Difference in C#
- Date and Time Format in C#
How to change DateTime format in C#
Changing the serialization format of a DateTime object and parsing a string to a DateTime object can be a challenging task when you are developing a multi-lingual large-scale application . For example, 3rd party libraries might use different culture settings. Your database connection might need a specific datetime format. Users or clients might prefer different datetime formats.
For these reasons, you should be careful about handling DateTime formatting issues, while you are developing a multi-lingual application in .Net environment (e.g. C# language). Displayed datetime formats, processed datetime formats, and stored datetime formats can be different.
There are several methods to manage DateTime format in C# programming language.
Changing DateTime format with String.Format
Here is the example code:
DateTime dt = DateTime . Now ; String . Format ( "{0:y yy yyy yyyy}" , dt); // 20 20 2020 2020
Changing DateTime format using ToString() method
Another style of changing the format is:
dt. ToString ( "MMMM dd, yyyy" ); // February 28, 2020
Change .Net DateTime to Microsoft SQL (MSSQL) Date/Time format
dt. ToString ( "yyyy-MM-dd HH:mm:ss" ); // 2020-02-28 16:13:47
The list of available datetime format specifiers are given below:
Editing Current Culture to manage DateTime format
To change the DateTime format in the application-wide, you need to edit the current culture of the application. Here is an example of this:
String culture = "af-ZA" ; Thread . CurrentThread . CurrentCulture = CultureInfo . CreateSpecificCulture (culture); Console . WriteLine (culture + " ---> " + DateTime . Now );
You may also change the DateTime format for the GUI thread:
Thread . CurrentThread . CurrentUICulture = ...
Available DateTime formats for the given culture strings are listed below:
af-ZA ---> 2013/12/31 06:07:09 NM. af-ZA ---> 2013/12/31 06:07:09 NM. ar-SA ---> 28/02/35 06:07:09 ? ar-AE ---> 31/12/2013 06:07:09 ? ar-BH ---> 31/12/2013 06:07:09 ? ar-DZ ---> 31-12-2013 18:07:09 ar-EG ---> 31/12/2013 06:07:09 ? ar-IQ ---> 31/12/2013 06:07:09 ? ar-JO ---> 31/12/2013 06:07:09 ? ar-KW ---> 31/12/2013 06:07:09 ? ar-LB ---> 31/12/2013 06:07:09 ? ar-LY ---> 31/12/2013 06:07:09 ? ar-MA ---> 31-12-2013 18:07:09 ar-OM ---> 31/12/2013 06:07:09 ? ar-QA ---> 31/12/2013 06:07:09 ? ar-SA ---> 28/02/35 06:07:09 ? ar-SY ---> 31/12/2013 06:07:09 ? ar-TN ---> 31-12-2013 18:07:09 ar-YE ---> 31/12/2013 06:07:09 ? az-Latn-AZ ---> 31.12.2013 18:07:09 az-Cyrl-AZ ---> 31.12.2013 18:07:09 az-Latn-AZ ---> 31.12.2013 18:07:09 be-BY ---> 31.12.13 18:07:09 be-BY ---> 31.12.13 18:07:09 bg-BG ---> 31.12.2013 г. 18:07:09 bs-Latn-BA ---> 31.12.2013 18:07:09 ca-ES ---> 31/12/2013 18:07:09 ca-ES ---> 31/12/2013 18:07:09 cs-CZ ---> 31. 12. 2013 18:07:09 cs-CZ ---> 31. 12. 2013 18:07:09 cy-GB ---> 31/12/13 18:07:09 da-DK ---> 31-12-2013 18:07:09 da-DK ---> 31-12-2013 18:07:09 de-DE ---> 31.12.2013 18:07:09 de-AT ---> 31.12.2013 18:07:09 de-DE ---> 31.12.2013 18:07:09 de-CH ---> 31.12.2013 18:07:09 de-LI ---> 31.12.2013 18:07:09 de-LU ---> 31.12.2013 18:07:09 dv-MV ---> 31/12/13 18:07:09 dv-MV ---> 31/12/13 18:07:09 el-GR ---> 31/12/2013 6:07:09 ?? el-GR ---> 31/12/2013 6:07:09 ?? en-US ---> 12/31/2013 6:07:09 PM en-029 ---> 31/12/2013 18:07:09 en-AU ---> 31/12/2013 6:07:09 PM en-BZ ---> 31/12/2013 06:07:09 PM en-CA ---> 2013-12-31 6:07:09 PM en-GB ---> 31/12/2013 18:07:09 en-IE ---> 31/12/2013 18:07:09 en-JM ---> 31/12/2013 18:07:09 en-NZ ---> 31/12/2013 6:07:09 p.m. en-PH ---> 12/31/2013 6:07:09 PM en-TT ---> 31/12/2013 06:07:09 PM en-ZA ---> 2013-12-31 06:07:09 PM en-ZW ---> 31/12/2013 6:07:09 PM es-ES ---> 31/12/2013 18:07:09 es-AR ---> 31/12/2013 06:07:09 p.m. es-BO ---> 31/12/2013 06:07:09 p.m. es-CL ---> 31-12-2013 18:07:09 es-CO ---> 31/12/2013 6:07:09 p. m. es-CR ---> 31/12/2013 06:07:09 p.m. es-DO ---> 31/12/13 6:07:09 p. m. es-EC ---> 31/12/2013 18:07:09 es-ES ---> 31/12/2013 18:07:09 es-GT ---> 31/12/2013 6:07:09 p. m. es-HN ---> 31/12/2013 06:07:09 p.m. es-MX ---> 31/12/2013 06:07:09 p. m. es-NI ---> 31/12/2013 06:07:09 p.m. es-PA ---> 31/12/13 6:07:09 p. m. es-PE ---> 31/12/2013 06:07:09 p.m. es-PR ---> 31/12/2013 06:07:09 p.m. es-PY ---> 31/12/2013 06:07:09 p.m. es-SV ---> 31/12/2013 06:07:09 p.m. es-UY ---> 31/12/2013 18:07:09 es-VE ---> 31-12-2013 06:07:09 p.m. et-EE ---> 31.12.2013 18:07:09 et-EE ---> 31.12.2013 18:07:09 eu-ES ---> 2013/12/31 18:07:09 eu-ES ---> 2013/12/31 18:07:09 fa-IR ---> 31/12/2013 06:07:09 ?.? fa-IR ---> 31/12/2013 06:07:09 ?.? fi-FI ---> 31.12.2013 18:07:09 fi-FI ---> 31.12.2013 18:07:09 fo-FO ---> 31-12-2013 18:07:09 fo-FO ---> 31-12-2013 18:07:09 fr-FR ---> 31/12/2013 18:07:09 fr-BE ---> 31-12-13 18:07:09 fr-CA ---> 2013-12-31 18:07:09 fr-FR ---> 31/12/2013 18:07:09 fr-CH ---> 31.12.2013 18:07:09 fr-LU ---> 31/12/2013 18:07:09 fr-MC ---> 31/12/2013 18:07:09 gl-ES ---> 31/12/2013 18:07:09 gl-ES ---> 31/12/2013 18:07:09 gu-IN ---> 31-12-13 18:07:09 gu-IN ---> 31-12-13 18:07:09 he-IL ---> 31/12/2013 18:07:09 he-IL ---> 31/12/2013 18:07:09 hi-IN ---> 31-12-2013 18:07:09 hi-IN ---> 31-12-2013 18:07:09 hr-HR ---> 31.12.2013. 18:07:09 hr-BA ---> 31.12.2013. 18:07:09 hr-HR ---> 31.12.2013. 18:07:09 hu-HU ---> 2013.12.31. 18:07:09 hu-HU ---> 2013.12.31. 18:07:09 hy-AM ---> 31.12.2013 18:07:09 hy-AM ---> 31.12.2013 18:07:09 id-ID ---> 31/12/2013 18:07:09 id-ID ---> 31/12/2013 18:07:09 is-IS ---> 31.12.2013 18:07:09 is-IS ---> 31.12.2013 18:07:09 it-IT ---> 31/12/2013 18.07.09 it-CH ---> 31.12.2013 18:07:09 it-IT ---> 31/12/2013 18.07.09 ja-JP ---> 2013/12/31 18:07:10 ja-JP ---> 2013/12/31 18:07:10 ka-GE ---> 31.12.2013 18:07:10 ka-GE ---> 31.12.2013 18:07:10 kk-KZ ---> 31-жел-13 18:07:10 kk-KZ ---> 31-жел-13 18:07:10 kn-IN ---> 31-12-13 18:07:10 kn-IN ---> 31-12-13 18:07:10 ko-KR ---> 2013-12-31 ?? 6:07:10 kok-IN ---> 31-12-2013 18:07:10 kok-IN ---> 31-12-2013 18:07:10 ko-KR ---> 2013-12-31 ?? 6:07:10 ky-KG ---> 31-дек 13 18:07:10 ky-KG ---> 31-дек 13 18:07:10 lt-LT ---> 2013-12-31 18:07:10 lt-LT ---> 2013-12-31 18:07:10 lv-LV ---> 31.12.2013. 18:07:10 lv-LV ---> 31.12.2013. 18:07:10 mi-NZ ---> 31/12/2013 6:07:10 p.m. mk-MK ---> 31.12.2013 18:07:10 mk-MK ---> 31.12.2013 18:07:10 mn-MN ---> 2013-12-31 18:07:10 mr-IN ---> 31-12-2013 18:07:10 ms-MY ---> 31/12/2013 18:07:10 ms-BN ---> 31/12/2013 18:07:10 ms-MY ---> 31/12/2013 18:07:10 mt-MT ---> 31/12/2013 18:07:10 nb-NO ---> 31.12.2013 18:07:10 nl-NL ---> 31-12-2013 18:07:10 nl-BE ---> 31/12/2013 18:07:10 nl-NL ---> 31-12-2013 18:07:10 nn-NO ---> 31.12.2013 18:07:10 nb-NO ---> 31.12.2013 18:07:10 pa-IN ---> 31-12-13 ??? 06:07:10 pa-IN ---> 31-12-13 ??? 06:07:10 pl-PL ---> 2013-12-31 18:07:10 pl-PL ---> 2013-12-31 18:07:10 pt-BR ---> 31/12/2013 18:07:10 pt-BR ---> 31/12/2013 18:07:10 pt-PT ---> 31/12/2013 18:07:10 quz-BO ---> 31/12/2013 06:07:10 p.m. quz-EC ---> 31/12/2013 18:07:10 quz-PE ---> 31/12/2013 06:07:10 p.m. ro-RO ---> 31.12.2013 18:07:10 ru-RU ---> 31.12.2013 18:07:10 sa-IN ---> 31-12-2013 18:07:10 sa-IN ---> 31-12-2013 18:07:10 se-FI ---> 31.12.2013 18:07:10 se-NO ---> 31.12.2013 18:07:10 se-SE ---> 2013-12-31 18:07:10 sk-SK ---> 31.12.2013 18:07:10 sk-SK ---> 31.12.2013 18:07:10 sl-SI ---> 31.12.2013 18:07:10 sl-SI ---> 31.12.2013 18:07:10 sma-NO ---> 31.12.2013 18:07:10 sma-SE ---> 2013-12-31 18:07:10 smj-NO ---> 31.12.2013 18:07:10 smj-SE ---> 2013-12-31 18:07:10 smn-FI ---> 31.12.2013 18:07:10 sms-FI ---> 31.12.2013 18:07:10 sq-AL ---> 31.12.2013 18:07:10 sq-AL ---> 31.12.2013 18:07:10 sr-Latn-CS ---> 31.12.2013. 18:07:10 sr-Cyrl-BA ---> 31.12.2013. 18:07:10 sr-Cyrl-CS ---> 31.12.2013. 18:07:10 sr-Latn-BA ---> 31.12.2013. 18:07:10 sr-Latn-CS ---> 31.12.2013. 18:07:10 sv-SE ---> 2013-12-31 18:07:10 sv-FI ---> 31.12.2013 18:07:10 sv-SE ---> 2013-12-31 18:07:10 sw-KE ---> 12/31/2013 6:07:10 PM sw-KE ---> 12/31/2013 6:07:10 PM syr-SY ---> 31/12/2013 06:07:10 ?.? syr-SY ---> 31/12/2013 06:07:10 ?.? ta-IN ---> 31-12-2013 18:07:10 ta-IN ---> 31-12-2013 18:07:10 te-IN ---> 31-12-13 18:07:10 te-IN ---> 31-12-13 18:07:10 th-TH ---> 31/12/2556 18:07:10 th-TH ---> 31/12/2556 18:07:10 tn-ZA ---> 31/12/13 06:07:10 Mo Maitseboeng tr-TR ---> 31.12.2013 18:07:10 tt-RU ---> 31.12.2013 18:07:10 tt-RU ---> 31.12.2013 18:07:10 uk-UA ---> 31.12.2013 18:07:10 uk-UA ---> 31.12.2013 18:07:10 ur-PK ---> 31/12/2013 6:07:10 PM ur-PK ---> 31/12/2013 6:07:10 PM uz-Latn-UZ ---> 31.12.2013 18:07:10 uz-Cyrl-UZ ---> 31.12.2013 18:07:10 uz-Latn-UZ ---> 31.12.2013 18:07:10 vi-VN ---> 31/12/2013 6:07:10 CH vi-VN ---> 31/12/2013 6:07:10 CH xh-ZA ---> 2013/12/31 06:07:10 Emva Kwemini zh-CN ---> 2013/12/31 18:07:10 zh-HK ---> 31/12/2013 18:07:10 zh-MO ---> 31/12/2013 18:07:10 zh-SG ---> 31/12/2013 ?? 6:07:10 zh-TW ---> 2013/12/31 ?? 06:07:10 zu-ZA ---> 31-12-2013 06:07:10 Ekuseni
Contents related to ' How to change DateTime format in C# '
How to change number decimal seperator in C#? : This document explains how to change the number decimal seperator of the double and floating points in c# applications.
Converting String to Double in C# : Several example codes that are parsing string to double in C# language.
How to convert date object to string in C#?
Here you will learn how to convert a DateTime object to a string in C#.
The DateTime struct includes the following methods that return date and time as a string.
Convert DateTime to String using the ToString() Method
Use the DateTime.ToString() method to convert the date object to string with the local culture format. The value of the DateTime object is formatted using the pattern defined by the DateTimeFormatInfo.ShortDatePattern property associated with the current thread culture. For example, the culture on your local/server environment is set to en-US , then you will get the string value of a date in MM/DD/YYYY format using any of the above methods.
The following converts the date portion of a DateTime object into a string.
In the above example, the ToString() method converts a date to a string based on the DateTimeFormatInfo.ShortDatePattern property of the current thread culture by default.
Convert DateTime to String in Specific Format
You can specify the specific date and time formats in the ToString() method to get a date and time string into a particular format. The following example demonstrates getting date value as a string in different formats using the ToString() method.
Visit date and time format specifiers to know all the format specifiers that can be used with the ToString() method.
Convert DateTime to Date String
Use the ToShortDateString() or ToLongDateString() to get the string of date portion in a short or long format based on your local culture, as shown below.
The ToShortDateString() method uses the ShortDatePattern and the ToLongDateString() method uses the LongDatePattern property property associated with the current thread culture.
Convert DateTime to Time String
Use the ToShortTimeString() or ToLongTimeString() to get the string of time portion in a short or long format based on your local culture, as shown below.
The ToShortTimeString() method uses the pattern defined by the ShortTimePattern property and the ToLongTimeString() method uses the LongTimePattern property associated with the current thread culture.
Use the ToString() method to convert a date object to different formats as per your need. Use ToShortDateString() or ToShortTimeString() to get short date and time string. Use ToLongDateString() or ToLongTimeString() to get the date and time in long format.
- Static vs Singleton in C#
- Difference between == and Equals() Method in C#
- Asynchronous programming with async, await, Task in C#
- How to loop through an enum in C#?
- Generate Random Numbers in C#
- Difference between Two Dates in C#
- Convert int to enum in C#
- BigInteger Data Type in C#
- Convert String to Enum in C#
- Convert an Object to JSON in C#
- Convert JSON String to Object in C#
- DateTime Formats in C#
- Compare strings in C#
- How to count elements in C# array?
- Difference between String and string in C#.
- How to get a comma separated string from an array in C#?
- Boxing and Unboxing in C#
- How to convert string to int in C#?
- How to calculate the code execution time in C#?

tutorialsteacher.com is a free self-learning technology web site for beginners and professionals.
- Entrepreneur
- Productivity
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- C# | IsNullOrEmpty() Method
- Difference between Abstract Class and Interface in C#
- String.Split() Method in C# with Examples
- C# | How to check whether a List contains a specified element
- C# | Arrays of Strings
- C# Dictionary with examples
- C# | Method Overriding
- C# | String.IndexOf( ) Method | Set - 1
- Different ways to sort an array in descending order in C#
- C# | Abstract Classes
- Introduction to .NET Framework
- C# | Replace() Method
- Difference between Ref and Out keywords in C#
- C# | Delegates
- C# | Constructors
- How to Extract filename from a given path in C#
- How to find the length of an Array in C#
- C# | String.Contains() Method
- C# | IsNullOrWhiteSpace() Method
- C# | Data Types
- C# | Arrays
- C# | Substring() Method
- C# | Class and Object
- Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
- Common Language Runtime (CLR) in C#
- C# | Encapsulation
- HashSet in C# with Examples
- C# | Method Overloading
- C# | Inheritance
- C# | Math.Pow() Method
C# Program to Display Date in String
- Last Updated : 27 Dec, 2021
System namespace and mscorlib.dll assembly in C# language provide a variety of classes and structures. It also provides DateTime struct using which we can initialize Data and Time objects. Using this struct we can also determine the year, month, weekday, etc.
1. DateTime Constructor: DateTime constructor is used for initializing an instance of the DateTime struct. The constructor method accepts year, month, day, time as parameters.
DateTime myDate = new DateTime(YYYY, MM, DD);
Note that the DateTime struct consists of a total of eleven overloaded constructors defined for different purposes. This article only focuses upon how we can display Date in string format in C# so we would not discuss all the remaining constructors.
2. DateTime.now() method: To get the current date and time DateTime.now() method of the DateTime struct is used. It returns an object of the DateTime struct which can be presented as a string using the ToString() method as explained below.
DateTime.now(format);
Return type: Returns an object of DateTime struct that contains the current date and time
3. ToString() method: This is quite useful whenever we want to print an object in string format. This method is used to convert the current DateTime object value to a string using the specified format.
DateTime.ToString(format);
Return type: Returns a string that represents the current date and time
Displaying date as a string in C#
There are numerous formats to display a date in the console. For example, Date/Month/Year, Month/Date/Year, etc. C# provides a number of overloaded DateTime.now() constructor methods that help to print date in various formats. Some of the commonly used methods are discussed below in detail:
1. This method is used to create an object of DateTime struct that contains current data in the format “Month/Day/Year”. Since it returns an instance of the DateTime struct so we can use it as a string by using the ToString() method. For example, 12/04/2021.
DateTime.Now.ToString(“MM/dd/yyyy”)
Return type: Returns a string format of the current date
2. This method is used to create an object of DateTime struct that contains current data in the format “Month Date”. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, December 04
DateTime.Now.ToString(“MMMM dd”)
3. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Saturday,03 December 2021 04:10 AM
DateTime.Now.ToString(“dddd, dd MMMM yyyy”)
4. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Saturday, 04 December 2021 06:40:59
DateTime.Now.ToString(“dddd, dd MMMM yyyy HH:mm:ss”)
5. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 06:41
DateTime.Now.ToString(“MM/dd/yyyy HH:mm”)
6. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 06:44 AM
DateTime.Now.ToString(“MM/dd/yyyy hh:mm tt”)
7. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 12/04/2021 6:44
DateTime.Now.ToString(“MM/dd/yyyy H:mm”)
8. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 2021’-‘12’-‘04’T’07’:’33’:’15.9841280+00:00
DateTime.Now.ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK”)
9. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, Sat, 04 Dec 2021 07’:’34’:’42 ‘G12T
DateTime.Now.ToString(“ddd, dd MMM yyy HH’:’mm’:’ss ‘GMT”)
10. This method is used to create an object of the DateTime struct that contains current data in the format. Since it returns an instance of the DateTime struct so we can use it as a string using the ToString() method. For example, 2021’-‘12’-‘04’T’07’:’41’:’12
DateTime.Now.ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss”)
Below is the implementation to illustrate these methods.
Please Login to comment...
- surinderdawra388
- CSharp-Strings-Programs
- C# Programs
New Course Launch!
Improve your Coding Skills with Practice
Start your coding journey now.
C# string转换为DateTime字符串格式总结

字符串转换为DateTime总结 1、年月日转换,中间可以有 "." "/" "-" " " (点,斜杠,横线,空格),只有无间距会报错 2、时间转化 中间必须是 ":"(冒号) 其他都会报错 3、日期和小时中间必须有 "T" 或" "(T或空格)
“相关推荐”对你有帮助么?

请填写红包祝福语或标题

你的鼓励将是我创作的最大动力

您的余额不足,请更换扫码支付或 充值

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。


IMAGES
VIDEO
COMMENTS
4 Answers Sorted by: 36 If you already have it as a DateTime, use: string x = dt.ToString ("yyyy-MM-dd"); See the MSDN documentation for more details. You can specify CultureInfo.InvariantCulture to enforce the use of Western digits etc.
To format it, you can first convert it to a DateTime (it's probably the simplest way). var birthdayString = "06/28/2013"; var date = Convert.ToDateTime (birthdayString); date.ToString ("dd/MM - MMMM d"); // 28/06 - June 28 date.ToString ("dd/MM/yyyy"); // 28/06/2013
C# DateTime date1 = new DateTime (2008, 1, 2, 6, 30, 15); Console.WriteLine (date1.ToString ("dd, MM", CultureInfo.InvariantCulture)); // 02, 01 Back to table The "ddd" custom format specifier The "ddd" custom format specifier represents the abbreviated name of the day of the week.
You can determine the custom format string or strings that correspond to a standard format string by calling the DateTimeFormatInfo.GetAllDateTimePatterns (Char) method. The following example displays the custom format strings that map to the "d" (short date pattern) standard format string. 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.
All formatting can be done also using DateTime.ToString method. Custom DateTime Formatting There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).
Standard DateTime Formatting in C#. Standard date and time format specifiers consist always of a single character that defines a particular string representation of a DateTime or DateTimeOffset value: var datetime = new DateTime(2017, 8, 24); Console.WriteLine(datetime.ToString("d")); // 8/24/2017. This formatting operation uses the default or ...
Here we see all the patterns of the C# DateTime, format, and results. d -> Represents the day of the month as a number from 1 through 31. dd -> Represents the day of the month as a number from 01 through 31. ddd -> Represents the abbreviated name of the day (Mon, Tues, Wed, etc). dddd -> Represents the full name of the day (Monday, Tuesday, etc).
There are several methods to manage DateTime format in C# programming language. Changing DateTime format with String.Format Here is the example code: DateTime dt = DateTime. Now; String. Format ( " {0:y yy yyy yyyy}", dt); // 20 20 2020 2020 Changing DateTime format using ToString () method Another style of changing the format is: dt.
Convert DateTime to String using the ToString () Method Use the DateTime.ToString () method to convert the date object to string with the local culture format. The value of the DateTime object is formatted using the pattern defined by the DateTimeFormatInfo.ShortDatePattern property associated with the current thread culture.
This method is used to convert the current DateTime object value to a string using the specified format. Syntax: DateTime.ToString (format); Return type: Returns a string that represents the current date and time Displaying date as a string in C# There are numerous formats to display a date in the console.
In C#, a string can be converted to DateTime object using parsing methods provided by DateTime struct. Apart from these methods, we can convert a string to date using Convert. To DateTime () method which takes a string representation of a date as input and returns its equivalent DateTime object. Recommended Articles
本文介绍C#编程时,给定一个字符串,如何判断它是不是一个日期。本文将介绍两种方法,一个是判断字符串是否是时间,如果是就转换为一个时间变量,第二个方法是只作判断。在C#中,对格式的判断有一类专门函数,那就是TryParse。TryParse在各个不同的类型类(如int,string,DateTime)中,都是存在的。