Pirzada
Pirzada

Reputation: 4713

MVC C# DateTime formatting fix needed

As you can see in the below screen shot. I have Date which is 7/12/2011 12:00:00 AM. Date is described wrong even if I format it. 7 should be the day and 12 is the month.

How I fix that to get proper formatting for yellow return string?

Date formatting problem

In the below screen shot the Date is 28/12/2011 11:00 where 28 is day and 12 is month. Trying to convert that string into DateTime to save into SQL Server DateTime field but gives conversion problem. Anyone tell me why is that and How to fix it?

Date conversion

Solution:

I solved problem like below. When I want saving date in SQL Server 2008 r2 the default was saved like 2011-08-12 11:00:00.000 which was causing problem. I changed that formatting Date when it was going to be saved in SQL like below and it worked

DateTime n = Convert.ToDateTime(start_date);

            var h = String.Format("{0:dd/MM/yyyy}", n);

            if (start_date != "")
            {
                changedEvent.start_date = Convert.ToDateTime(h);
            }

Output now is 2011-12-08 11:00:00.000. Do you think any clean work around?

Upvotes: 1

Views: 1919

Answers (3)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

I think you are addressing the wrong problem. If you want DateTime to recognize your locale date format, then you should make sure the servers date locale is set for your local one. Then, DateTime will convert the date correctly without conversion.

If that's not possible (say you're using a shared server in a different locale) then the ParseExact method would be one solution, but it will only fix some of the problem. For instance, dates posted and model bound will attempt to parse in the servers locale format.

You may need to set your locale explicitly, using something like this:

Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-MX");

Upvotes: 0

ysrb
ysrb

Reputation: 6740

Try:

DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss TT", null); //28/12/2011 11:00:00 AM
DateTime.ParseExact(str, "dd/MM/yyyy HH:mm", null); //28/12/2011 11:00

Upvotes: 0

SLaks
SLaks

Reputation: 887195

You should call DateTime.ParseExact(start_date, "dd/MM/yyyy", CultureInfo.InvariantCulture)

Upvotes: 1

Related Questions