Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format (format,date) is ignoring format

Tags:

.net

datetime

Not sure what's going on here.

I have a DateTime object, and when I try:

String.Format( "{0:dd/MM/yyyy}", _date)

the value returned is:

"24-05-1967"

What I want is

"24/05/1967"

Can anyone explain why my format string is being ignored?

A bit more background: This is a web app which started out life as .net 1.1, and I'm in the process of moving it up to 2.0/3.5.

Update:

If I change the format to {0:dd:MM:yyyy}, it returns 24:05:1967 - it's only the / in the format string that gets changed to the - char.


Resolution:

When updating the app to run under 2.0, the asp.net globalization settings were messed up.

From the web site properties, ASP.NET tab, Edit Configuration, Application Tab - the culture and UI Culture were both set to the first item in the list (af-ZA) for some bizarre reason.

like image 686
chris Avatar asked Nov 25 '08 16:11

chris


People also ask

What is string date/time format?

A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.

What is string data format?

A date and time format string is a string of text used to interpret data values containing date and time information. Each format string consists of a combination of formats from an available format type. Some examples of format types are day of week, month, hour, and second.


1 Answers

The / is actually the date separator for your specific culture which could be -, in other words, the format string is not ignored but actually used correctly. Look at what CultureInfo is associated with the running thread:

System.Threading.Thread.CurrentThread.CurrentCulture

If you try this:

String.Format(new CultureInfo("en-US"), "{0:dd/MM/yyyy}", DateTime.Now);

You will get the date formatted with / since that is the correct separator for en-US. What you probably should do is use the short date format string and make sure that the thread has the appropriate culture associated, then this would get you what you want and it will work in a globalized application as well:

DateTime.Now.ToString("d", Thread.CurrentThread.CurrentCulture);

Hope this helps!

like image 72
Carl Serrander Avatar answered Sep 19 '22 14:09

Carl Serrander