开发者

how can i remove the time from the datetime

开发者 https://www.devze.com 2023-02-07 16:54 出处:网络
mvc - c# - aspx=> i have a DDL(drop down list), that shows the dates from a table, the DDL is used for filtering items shown in a table. the table works, the filters work, the only ugly thing is 开发

mvc - c# - aspx => i have a DDL(drop down list), that shows the dates from a table, the DDL is used for filtering items shown in a table. the table works, the filters work, the only ugly thing is 开发者_如何学编程that the filter shows a time with the date : 02/12/2010 12:00:00:00:00AM or something like that, i am trying to drop the time as it comes form the table, but if there is a better way please help, i have tried the following: in the controller => string.format :tells me that its not a valid sql what ever....ToString("MM/dd/yyyy", n) tells me the same, i also tried convert(varchar(12), n, 101) thinking that it might take the sql server but it didnt like that either, i even tried to add a format to the DDL key in the view file, and as i expected it said it could not find whatever with that key.

// target date -- this code is from my controller

    if ((Request.Form["TARGET_DATE"] != null) && Request.Form["TARGET_DATE"] != "")
    {
        TargetDate = Request.Form["TARGET_DATE"];
        ViewData["TARGET_DATE"] = new SelectList((from n in _db.ACTION_PLANs select n).ToList(), "TARGET_DATE", "TARGET_DATE", TargetDate);
        predicate = predicate.And(p => p.TARGET_DATE == Convert.ToDateTime(TargetDate));
    }
    else
    {
        TargetDate = null;
        ViewData["TARGET_DATE"] = new SelectList((from n in _db.ACTION_PLANs select n).ToList(), "TARGET_DATE", "TARGET_DATE");
    }

is there any way to format the 'n' to follow 'MM/dd/yyyy'? or how would be the best way to do this? or what am i doing wrong? .....thank you


Something you should understand is that both the SQL and CLR DateTime types are actually stored as an integer number containing the number of "ticks" relative to the "epoch". Thus, the time is inseparable from the date at this level; the value that represents the date and time is simply evenly divisible by the number of ticks in a day. There is no CLR type that is just a Date.

To "ignore" the time when converting it to a string, you can use the ToString() overload of DateTime: Convert.ToDateTime(TargetDate).ToString("MM/dd/yyyy"); However, unless you have also done that to p.TARGET_DATE, your comparison will likely fail.


I think you are not seeing what data types you are really getting. The output of "02/12/2010 12:00:00:00:00AM" looks like somethign is calling .ToString() behind the scenes on a type that eventually unboxes to a DateTime data type.

Based on the limited into you put in your description, try

((DateTime)ViewData["TARGET_DATE"])).ToString("MM/dd/yyyy")

Maybe you get lucky and that works. Or try some overkill with this:

DateTime.Parse(ViewData["TARGET_DATE"].ToString()).ToString("MM/dd/yyyy")

Wither way, both examples are very bad code, it's just to enable to you start solving the problem (ie, use TryParse() on the second example, or use the "as" keyword in the first example). In your cleaned up version use full error checking, including checking for null/empty/DBNull.Value values.

In both cases, the point is to figure out the real data type you are getting (perhaps Object?) and then convert/cast it so you can format it as you really want it.


"Dropping the time" on the way out of the database will just set the time component to 0 - i.e. midnight or 12:00:00.000AM.

You'll need to sort out the format in the presentation layer so that only the date is represented.


thanks every one that helped... i was finally able to get the date to show without the time in my dropdownlist(DDL). this is how i did it.

        if ((Request.Form["TARGET_DATE"] != null) && Request.Form["TARGET_DATE"] != "")
    {
        TargetDate = Request.Form["TARGET_DATE"];

        IEnumerable<SelectListItem> tarDate =
            from n in _db.ACTION_PLANs
            select new SelectListItem
            {
                Selected = (TargetDate == n.TARGET_DATE.Date.ToString()),
                Text = string.Format("{0:MM/dd/yyyy}", n.TARGET_DATE.Date),
                Value = n.TARGET_DATE.ToString(),
            };


        ViewData["TARGET_DATE"] = tarDate;

        predicate = predicate.And(p => p.TARGET_DATE.ToString() == TargetDate);

i hope that this also helps other people that were having the same issue.


The .ToString method accepts an optional versatile formatting parameter.

To remove the time component in your output string then you may use .ToString("MM/dd/yyyy").

Example

In the following example I acheive the following goals:

  1. Set the TargetDate attribute based on whether the TARGET_DATE session parameter exists.

  2. Create the initial List of DateTime and populate it with the result of your TARGET_DATE session parameter based linq query.

  3. I create a new List of string and copy the List of DateTime, applying the desired formatting.

  4. List of string is then resady to be used as the datasource for the drop-down list.

  5. I'm unsure as to the purpose of the TARGET_DATE session parameter based line of code that sets the variable predicate. I left it in in case the surrounding code requires it.

Code

Having edited the supplied code, please use the following amended code:

bool IsDateset = (Request.Form["TARGET_DATE"] != null) && Request.Form["TARGET_DATE"] != "";

TargetDate = IsDateset ? Request.Form["TARGET_DATE"] : null;

List<DateTime> TargetDatesAsDateTime = null;

if (IsDateset)
{
    List<DateTime> TargetDatesAsDateTime = new SelectList((from n in _db.ACTION_PLANs select n).ToList(), "TARGET_DATE", "TARGET_DATE", TargetDate);

    predicate = predicate.And(p => p.TARGET_DATE == Convert.ToDateTime(TargetDate)); // I'm unsure as to the purpose of this line of code. I left it in in case the surrounding code requires it.

}
else
{
    List<DateTime> TargetDatesAsDateTime = new SelectList((from n in _db.ACTION_PLANs select n).ToList(), "TARGET_DATE", "TARGET_DATE");

}

List<string> TargetDateAsString = new List<string>();

if(TargetDatesAsDateTime != null || TargetDatesAsDateTime.Count > 0)
{           
    foreach(DateTime d in TargetDatesAsDateTime)
    {
        //string s = d.ToString("yyyy/MM/dd"); // Japan variant
        //string s = d.ToString("dd/MM/yyyy"); // England variant
        string s = d.ToString("MM/dd/yyyy"); // American variant

        TargetDateAsString.Add(s);

    }

}

ViewData["TARGET_DATE"] = TargetDatesAsString;

I'll leave it to you to reduce and format the code to your preference.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号