Как преобразовать datetime в string c
Перейти к содержимому

Как преобразовать datetime в string c

  • автор:

How to Convert a DateTime Object to a String in C#

In this tutorial, we will look at various ways and alternatives for converting DateTime objects to strings in C#, so you can deal successfully with dates and times in your applications.

Convert a DateTime Object to a String

In C#, the following methods are used to convert a DateTime object to a string:

1: Using the ToString Method with a Format String

The ToString() method in C# provides a powerful way to format and convert a DateTime object into a string. With the help of format strings, you can customize the output format of the date and time values to display them in a more readable and understandable format.

The following code example illustrates the implementation of the ToString() method:

namespace MyApplication
{
class Program
{
static void Main ( string [ ] args )
{
DateTime currentDate = DateTime.Now;
string formattedDate = currentDate.ToString ( "dd/MM/yyyy HH:mm:ss" ) ;
Console.WriteLine ( "Formatted date: " + formattedDate ) ;
}
}
}

In the preceding code snippet, we generate a DateTime object through the utilization of the DateTime.Now property. Then the ToString() method is invoked on the DateTime object utilizing the format string “dd/MM/yyyy HH:mm:ss” to format the date and time value into a string according to the specified format. The resulting formatted date and time value is assigned to the formattedDate variable. Finally, the Console.WriteLine() method outputs the formatted date and time value to the console.

Output

2: Using the ToString Method with a Format Provider

In C#, you can also use a format provider to convert a DateTime object to a string, which is an object that provides formatting information, such as a culture-specific format.

Below is a code snippet that demonstrates the usage of a format provider to convert a DateTime object into a string:

The above code utilizes the System and System.Globalization namespaces to obtain the current date and time using the DateTime.Now property. The CultureInfo.CurrentCulture property is then used to set the culture to “en-US“, and the DateTime value is converted to a string using the ToString() method and the “G” format specifier.

Output

3: Using the String Interpolation

Another technique to convert a DateTime object into a string in C# involves the utilization of string interpolation. This approach entails embedding expressions inside string literals and simplifies the process of constructing strings with variables and expressions.

The following code snippet provides an illustration of how to implement string interpolation to convert a DateTime object into a string:

namespace MyApplication
{
class Program
{
static void Main ( string [ ] args )
{
DateTime dt = DateTime.Now;
string dtString = $ "" ;
Console.WriteLine ( "DateTime as string: <0>" , dtString ) ;
}
}
}

The above code creates a DateTime object representing the current date and time. The ToString() method is not explicitly called on the DateTime object, but instead, the string interpolation syntax is used to format the DateTime object into a string with the format string “yyyy-MM-dd HH:mm:ss“.

The resulting formatted date and time value is assigned to the dtString variable, and then output to the console using the Console.WriteLine() method.

Output

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

Conclusion

Converting a DateTime object to a string in C# can be done using the ToString() method with a format string, a format provider, or string interpolation. These techniques allow for customization of the date and time output format for better readability and understanding. Acquiring knowledge of these methods equips you with the ability to work proficiently with dates and times within your C# applications.

About the author

Awais Khan

I’m an Engineer and an academic researcher by profession. My interest for Raspberry Pi, embedded systems and blogging has brought me here to share my knowledge with others.

# DateTime Methods

DateTimeForma­tInfo specifies a set of specifiers for simple date and time formating. Every specifier correspond to a particular DateTimeFormatInfo format pattern.

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)
  • z (time zone).

You can use also date separator / (slash) and time sepatator : (colon).

For more information MSDN

# DateTime.AddDays(Double)

Add days into a dateTime object.

You also can subtract days passing a negative value:

# DateTime.AddHours(Double)

# DateTime.Parse(String)

# DateTime.TryParse(String, DateTime)

# DateTime.AddMilliseconds(Double)

# DateTime.Compare(DateTime t1, DateTime t2 )

# DateTime.DaysInMonth(Int32, Int32)

# DateTime.AddYears(Int32)

Add years on the dateTime object:

# Pure functions warning when dealing with DateTime

Wikipedia currently defines a pure function as follows:

  1. The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices .
  2. Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices

As a developer you need to be aware of pure methods and you will stumble upon these a lot in many areas. One I have seen that bites many junior developers is working with DateTime class methods. A lot of these are pure and if you are unaware of these you can be in for a suprise. An example:

Given the example above one may expect the result printed to console to be ’26/12/2016′ but in reality you end up with the same date. This is because AddDays is a pure method and does not affect the original date. To get the expected output you would have to modify the AddDays call to the following:

# DateTime.TryParseExact(String, String, IFormatProvider, DateTimeStyles, DateTime)

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly. The method returns a value that indicates whether the conversion succeeded.

Как преобразовать datetime в string c

This method is used to Converts the value of the current DateTime object to its equivalent string representation. There are total 4 methods in the overload list of this method:

  • ToString(String, IFormatProvider)
  • ToString(String)
  • ToString(IFormatProvider)
  • ToString()

Here, we will discuss only first two methods.

ToString(String, IFormatProvider)

This method is used to convert the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information.

Syntax: public string ToString (string format, IFormatProvider provider);
Parameters:
format: A standard or custom date and time format string.
provider: An object that supplies culture-specific formatting information.
Return Value: This method returns a string representation of the value of the current DateTime object as specified by format and provider.

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.

Method Description
DateTime.ToString() Converts a DateTime value to a string in the specified format of the current culture.
DateTime.ToShortDateString() Converts a DateTime value to a short date string (M/d/yyyy pattern) in the current culture.
DateTime.ToShortTimeString() Converts a DateTime value to a short time string (h:mm:ss pattern) in the current culture.
DateTime.ToLongDateString() Converts a DateTime value to a long date string (dddd, MMMM d, yyyy pattern) in the current culture.
DateTime.ToLongTimeString() Converts a DateTime value to a long time string (h:mm:ss tt pattern) in the current culture.

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.

Conclusion

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *