1

I have a windows service application in which I am getting the current date and time using DateTime.Now.ToString(), which returns '04-05-2018 05:50:12'.

But I tried the same in a sample console application, but it returns the date in a different format as '5/4/2018 5:51:32 AM'

Both these machines are being executed in the same machine. Can some one let me know why is there a date format difference in these applications?

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Ravish R
  • 19
  • 1

1 Answers1

2


The DateTime.ToString() formats the DateTime according to current culture. As Written in the Documentation

Converts the value of the current DateTime object to its equivalent string representation using the formatting conventions of the current culture.(Overrides ValueType.ToString().)

If you want the same string you should instead use the DateTime.ToString(string) overload and provide the exact format which you want.

The ToString(String) method returns the string representation of a date and time value in a specific format that uses the formatting conventions of the current culture; for more information, see CultureInfo.CurrentCulture.

The format parameter should contain either a single format specifier character (see Standard Date and Time Format Strings) or a custom format pattern (see Custom Date and Time Format Strings) that defines the format of the returned string. If format is null or an empty string, the general format specifier, 'G', is used.

Some uses of this method include:

Getting a string that displays the date and time in the current culture’s short date and time format. To do this, you use the “G” format specifier.

Getting a string that contains only the month and year. To do this, you use the “MM/yyyy” format string. The format string uses the current culture’s date separator.

Getting a string that contains the date and time in a specific format. For example, the “MM/dd/yyyyHH:mm” format string displays the date and time string in a fixed format such as “19//03//2013 18:06". The format string uses “/” as a fixed date separator regardless of culture-specific settings.

Getting a date in a condensed format that could be used for serializing a date string. For example, the "yyyyMMdd" format string displays a four-digit year followed by a two-digit month and a two-digit day with no date separator.

Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
  • This doesn't answer the question, though. The question is, why is it different between a Windows Service application and a Console application _on the same machine_? In theory, the current culture should be same for both applications. – Chris Dunaway May 04 '18 at 16:32