[asp.net-mvc] How do I pass a datetime value as a URI parameter in asp.net mvc?

I need to have an action parameter that has a datetime value? Is there a standard way to do this? I need to have something like:

mysite/Controller/Action/21-9-2009 10:20

but I'm only succeeding indoing it with something like:

mysite/Controller/Action/200909211020

and writing a custome function to deal with this format.

Again, looking for a standard or sanctioned ASP.net MVC way to do this.

This question is related to asp.net-mvc datetime uri

The answer is


Split out the Year, Month, Day Hours and Mins

routes.MapRoute(
            "MyNewRoute",
            "{controller}/{action}/{Year}/{Month}/{Days}/{Hours}/{Mins}",
            new { controller="YourControllerName", action="YourActionName"}
        );

Use a cascading If Statement to Build up the datetime from the parameters passed into the Action

    ' Build up the date from the passed url or use the current date
    Dim tCurrentDate As DateTime = Nothing
    If Year.HasValue Then
        If Month.HasValue Then
            If Day.HasValue Then
                tCurrentDate = New Date(Year, Month, Day)
            Else
                tCurrentDate = New Date(Year, Month, 1)
            End If
        Else
            tCurrentDate = New Date(Year, 1, 1)
        End If
    Else
        tCurrentDate = StartOfThisWeek(Date.Now)
    End If

(Apologies for the vb.net but you get the idea :P)


i realize it works after adding a slash behind like so

mysite/Controller/Action/21-9-2009 10:20/

Since MVC 5 you can use the built in Attribute Routing package which supports a datetime type, which will accept anything that can be parsed to a DateTime.

e.g.

[GET("Orders/{orderDate:datetime}")]

More info here.


Try to use toISOString(). It returns string in ISO8601 format.

from javascript

$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
    console.log(result);
});

from c#

[HttpGet]
public JsonResult DoGet(DateTime date)
{
    return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}

I thought I'd share what works for me in MVC5 for anyone that comes looking for a similar answer.

My Controller Signature looks like this:

public ActionResult Index(DateTime? EventDate, DateTime? EventTime)
{

}

My ActionLink looks like this in Razor:

@Url.Action("Index", "Book", new { EventDate = apptTime, EventTime = apptTime})

This gives a URL like this:

Book?EventDate=01%2F20%2F2016%2014%3A15%3A00&EventTime=01%2F20%2F2016%2014%3A15%3A00

Which encodes the date and time as it should.


You should first add a new route in global.asax:


routes.MapRoute(
                "MyNewRoute",
                "{controller}/{action}/{date}",
                new { controller="YourControllerName", action="YourActionName", date = "" }
            );

The on your Controller:



        public ActionResult MyActionName(DateTime date)
        {

        }

Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.


Use the ticks value. It's quite simple to rebuild into a DateTime structure

 Int64 nTicks = DateTime.Now.Ticks;
 ....
 DateTime dtTime = new DateTime(nTicks);

I have the same problem. I use DateTime.Parse Method. and in the URL use this format to pass my DateTime parameter 2018-08-18T07:22:16

for more information about using DateTime Parse method refer to this link : DateTime Parse Method

string StringDateToDateTime(string date)
    {
        DateTime dateFormat = DateTime.Parse(date);
        return dateFormat ;
    }

I hope this link helps you.


Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer

I would suggest sending the date value as a parameter rather than as part of the route:

 mysite/Controller/Action?date=21-9-2009 10:20

If it's still giving you problems the date may contain characters that are not allowed in a URI and need to be encoded. Check out:

 encodeURIComponent(yourstring)

It is a method within Javascript.

On the Server Side:

public ActionResult ActionName(string date)
{
     DateTime mydate;
     DateTime.Tryparse(date, out mydate);
}

FYI, any url parameter can be mapped to an action method parameter as long as the names are the same.


Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to uri

Get Path from another app (WhatsApp) What is the difference between resource and endpoint? Convert a file path to Uri in Android How do I delete files programmatically on Android? java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder How to get id from URL in codeigniter? Get real path from URI, Android KitKat new storage access framework Use URI builder in Android or create URL with variables Converting of Uri to String How are parameters sent in an HTTP POST request?