简体   繁体   中英

Asp.net mvc3, C#, Datetime.Parse()

It is very weird. I hava date format data that comes from Http GET, and I wrap the date using model class. it is like this,

// Model

public class wrapModel
{
  public DateTime mydate{get; set;}
}

And,

// controller
[HttpGet]
public void myController(wrapModel data){
   Response.Write(searchModel.mydate.ToString());
}

and call the controller using browser, myhost/home/myController/mydate=05/05/2012

then it print "5/5/2012 12:00:00 AM" ,I expected 5/5/2012 only.

I do not need the time. so I tried to parse the date.

data.mydata = DateTime.parse(data.mydata.ToString("MM/dd/yyyy"));

but it still print "5/5/2012 12:00:00 AM"

How can I change the format to "5/5/2012"?

anybody know, please advice me~

Thank you!

I want to parse datetime format data that comes from Http GET.

but I does not changed and also

[EDIT]

Thank you for all the answers and your valuable time! but I am still in the problem. Please help me a little more :)

First of all, I need DateTime format data, not string type, becuase I will use the date in Linq to retrieve DB date.

I tried,

1)

[DisplayFormat(DataFormatString="{0:MM/dd/yyyy}", ApplyFormatInEditMode=true)]
public DateTime mydate { get; set; }

[HttpGet]
public ActionResult myController(wrapModel data){
   return Content(searchModel.mydate.ToString());
}

still it print "5/5/2012 12:00:00 AM"

2)

[HttpGet]
public ActionResult myController(wrapModel data){
   return Content(searchModel.mydate.ToString("MM/dd/yyyy"));
}

it changed foramt as well, but I need DateTime format so I convert to DateTime again.

[HttpGet]
public ActionResult myController(wrapModel data){
   searchModel.mydate = DateTime.Parse(searchModel.mydate.ToString("MM/dd/yyyy"));
   return Content(searchModel.mydate.ToString());
}

then it print "5/5/2012 12:00:00 AM" again.

3)

searchModel.etaDate.ToString("d")

same to above, convert to DateTime then it print "5/5/2012 12:00:00 AM"

And

I use Response.Write() for simple return value test, but is there any important reason I can not use the Response.Write() method? I want to learn :)

Thanks a lot!

[EDIT]

I need to DateTime type data for this,

Repository myRespository = new Respository();

var data = (from x in myRepository.myContext
            where x.thedate == mydate  // thedate is datetime type, so I need datetime type for compare
            select x.no).SingleOrDefault()

I tried,

string test = mydate.ToShortDateString();

(...
where x.thedate.ToString() == test
...)

but it does not work.

How can I change the format to "5/5/2012"?

You will first have to pass the parameter using the correct format which is always yyyy-MM-dd for GET requests:

http://myhost/home/myController/mydate=2012-05-05

I am stressing on the word always , because this is very important to understand. The reason for this is that the default model binder always uses InvariantCulture when parsing dates from GET requests and it uses the current culture when parsing dates from POST requests. There's a nice article explaining this as well as the reasons behind this design decision.

and then:

Response.Write(searchModel.mydate.ToString("MM/dd/yyyy"));

Well, actually, not Response.Write because you never do that in an ASP.NET MVC application, you'd rather return an ActionResult from a controller action:

[HttpGet]
public ActionResult MyAction(wrapModel data)
{
    return Content(data.mydate.ToString("MM/dd/yyyy"));
}

or you will have your view model decorated with the DisplayFormat attribute:

public class wrapModel
{
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime mydate { get; set; }
}

or if you want to take into account the current culture short date format:

public class wrapModel
{
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime mydate { get; set; }
}

and then have your controller action pass this model to the view:

public ActionResult MyAction(wrapModel data)
{
    return View(data);
}

and of course inside the corresponding strongly typed view use the DisplayFor / EditorFor helpers to achieve the desired output in the desired format:

@model wrapModel
<span>
    @Html.DisplayFor(x => x.mydate)
</span>

采用

datevar.ToShortDateString();

(Note: Darin's answer is great for MVC. I've posted this for more general information.)

but it still print "5/5/2012 12:00:00 AM"

Yes, it would. Just because you parsed a value which only has a date in, that isn't known to the DateTime value. That's just a date and time. If you call ToString on it, it will always use the default format for the current culture.

I would strongly advise you to avoid doing any more conversions to string than you absolutely have to. Parse the value as early as you can, then keep it as a DateTime internally until you absolutely have to convert it back to a string - either for use in a system which can't use the DateTime natively (eg saving to a file) or writing it back to a user.

If you are going to write it back to a user, you should make sure you use the appropriate culture for that user, and use an appropriate format string - eg d for "short date". While you can use ToShortDateString , that doesn't allow you to specify the culture, whereas ToString does:

string text = date.ToString("d", culture);

Anywhere you're not displaying the information to a user, I would strongly recommend using a standard format: "yyyy-MM-dd" for dates, and "yyyy-MM-dd'T'HH:mm:ss.fffffffK" for date/time values. (The latter is represented by the o standard format string.)

Note that the format is really important for dates. If you show me a web page with "08/07/2012" on, I won't know whether that's August 7th or July 8th.

解析后,请使用.ToShortDateString()

您应该在自己的视图中使用该代码:

item.mydate.Value.ToShortDateString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM