0

I'm trying to convert format of a DateTime on my asp.net mvc web app.

I've this code :

date = Request["date"].AsDateTime().ToString("MM-dd-yyyy HH:mm:ss");

That code works perfectly when the Request["date"] as only one digit for the day
(like 08-03-2016) but when the date hava two digits date ( like 15-03-2016 ),

it returns 01-01-0001... Can someone explains me why and tell me how to makeit better ?

Thanks in advance !

EDIT :

More of code I'm using :

Javascript date picker for the date selection:

<script>
    $(document).ready(function() {
        $('.date').datepicker({ dateFormat: "dd/mm/yy" });
    });
</script>

Code for format :

    String date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 0, 0, 0).ToString("dd/MM/yyyy HH:mm:ss");

string[] formats = { "dd-MM-yyyy" };
DateTime resultDate = new DateTime();
if (DateTime.TryParseExact(Request["date"], formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out resultDate))
            {
                //if everything good you will have your date in resultDate variable
                date = resultDate.ToString("MM-dd-yyyy HH:mm:ss");
            }
6
  • Most likely because the .AsDateTime() extension method is parsing the data using a culture which is MM-dd-yyyy - does 11-03-2016 work? Commented Mar 16, 2016 at 8:49
  • Why are you reading the query parameter from the Request object instead of using an action parameter? Why use a localized format either instead of eg. 2015-03-15 which can be parsed unambiguously? Commented Mar 16, 2016 at 8:50
  • Where does that parameter come from? If you change it to the ISO format, you could even use a DateTime-typed parameter in your action method Commented Mar 16, 2016 at 8:56
  • @StephenMuecke Yes 11-03-2016 is working Commented Mar 16, 2016 at 8:58
  • @PanagiotisKanavos I'm using the request because I'm using a javascript datepicker in my view and that's where the date come from. Commented Mar 16, 2016 at 9:00

3 Answers 3

4

.AsDateTime() Method using your current machine culture (It depends on your application App.Config or Web.Config).

If you 100% sure that you have your date in dd-MM-yyyy format you can parce it like this:

DateTime.ParseExact(Request["date"], "dd-MM-yyyy", CultureInfo.InvariantCulture)
.ToString("MM-dd-yyyy HH:mm:ss");

As Stephen Muecle mention it's better to use DateTime.TryParseExact() method:

//here you can define more that one format to parce
string[] formats = { "dd-MM-yyyy"};
DateTime resultDate = new DateTime();
if (DateTime.TryParseExact(Request["date"], formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out resultDate))
{
    //if everything good you will have your date in resultDate variable
    date = resultDate.ToString("MM-dd-yyyy HH:mm:ss"); 
}
else
{ 
    //here the logic if parce fails
}

Ok as Panagiotis Kanavos menthion it's not a good idea to Hard-coding the culture. If you want to do things right you should deal with globalization.

In your Web.Config you should set uiCulture and culture:

<globalization uiCulture="en-GB" culture="en-GB" />

And then when you init your jquery ui datepicker you should set current culture. Something like this:

$('.datepicker').datepicker({ dateFormat: '@System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern' });

If you set globalization in Web.Config your whoule app Culture will be sync and you will be able to use even .AsDateTime().

Sign up to request clarification or add additional context in comments.

10 Comments

TryParseExact() would be better to avoid any potential exception.
Hard-coding the date format is a bad idea. Far better to use the standard YYYY-MM-DD format
@StephenMuecke actually it would be worse, because it would allow processing even if the date literal was invalid - unless proper handling code was uses (eg check for missing, invalid values)
@PanagiotisKanavos, If you use TryParseExact() you can then test the result before using .ToString()
@PanagiotisKanavos agreed that it's better to use standart formats. But if you had to localize your application you had to sync your culture in all your app and get your format from System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.
|
0

Try this:

DateTime unformattedDate;
if(DateTime.TryParse(Request["date"], out unformattedDate)
{
   DateTime formattedDate = unformattedDate.ToString("MM-dd-yyyy HH:mm:ss");
}

1 Comment

Why wouldn't that fail in exactly the same way?
0

Try using this:

DateTime date = new DateTime();
date = (DateTime)Request["date"];
String myDate=date.ToString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.