简体   繁体   中英

How to get only date from date time using Asp. Net c#?

In sql database, value is in this format 2016-07-16 and it's datatype is date .

But when i am getting it gives me like that: 7/16/16 12:00:00 AM

I want to get only the date 2016-07-16 but with this format 16/07/2016 .

How to get it?

When you fetch the data from the sql you should manipulate the data and change this value. i don't know if your using linq or using EF.

if you use linq

var query = from p in db.table
            select new view{
               CreatedOn = p.CreatedOn.ToString("dd/MM/yyyy")
            };

but if you use EF and code first you can set the GET method on its property like this :

private DateTime _createdOn;

public string CreatedOn {

    get {
         return _createdOn.ToString("dd/MM/yyyy");
    }
    set{
        _createdOn = value;
    }

}

public string GetDateOnly(string DateString) {

    DateTime _retVal = Convert.ToDateTime(DateString);
    return _retVal.ToString('dd/MM/yyyy');

}

this this method where by passing datetime string

I had the same problem. This is what I did following @M.R.Safari using the Entity Framework migrations and code first approach.

    [Required]
    public DateTime StartDate { get; set; }
    public string StartDateShort
    {
        get
        {
            return StartDate.ToString("dd/MM/yyyy");
        }
        set
        {
            StartDateShort = value;
        }
    }
    [Required]
    public DateTime EndDate { get; set; }
    public string EndDateShort
    {
        get
        {
            return EndDate.ToString("dd/MM/yyyy");
        }
        set
        {
            EndDateShort = value;
        }
    }

I did get an error on the Set method using @M.R.Safari example since it was trying to overwrite the StartDate(DateTime) value to a String, so I instead used the Set method for the String version. I edit only the StartDate(DateTime) value in my forms and the string value gets updated automatically. I use the string value for views.

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