Search code examples
asp.netasp.net-mvcdatetimeculture

Asp.Net MVC DateTime culture issue


I am trying to show Month and year instead of Date in control on UI. Will this be a issue for the date if I do not specify culture explicitly. Will this break if server locale is changed? How do I manage in this case? What will be the better way to write the below code ?

[DisplayName("Delivery Month")]
public string DeliveryMonth
{
    get
    {
        return DeliveryDate.ToString("Y");
    }
    set
    {
        DeliveryDate = DateTime.Parse("1." + this.DeliveryMonth);
    }
}

public DateTime DeliveryDate { get; set; } 

Solution

  • In your model, you can set the DeliveryDate as string

    public string DeliveryDate { get; set; }
    

    Then in your view. you can add a textbox for your model that will turn into a datetimepicker control, through the use of jQuery.

    The html for the textbox:

    <div>
        @Html.TextBoxFor(model => Model.DeliveryDate,
        new { @class = "DeliveryDatePicker", style =  "width:50%;height:25px;background:transparent;padding:0;margin-left:5px;" })
        @Html.ValidationMessageFor(model => model.DeliveryDate)
    </div>
    

    The jQuery to be placed in the document load function:

    $("#DeliveryDate").datepicker({ dateFormat: 'dd/mm/yy' });
    

    The format of the datepicker - you can set it to whatever format you need - just moth and year in your case by using dateFormat(now.getMonth() + 1) and dateFormat(now.getYear() - 100) functions. e.g. to set it to the full date in jQuery it would be:

    $("#DeliveryDate").val(dateFormat(now.getDate()) + '/' + dateFormat(now.getMonth() + 1) + '/' + dateFormat(now.getYear() - 100));
    

    In your data access/repository get method, you will need to get it as string:

    deliveryModel.DeliveryDate = Convert.ToDateTime(sqlDataReader["DELIVERYDATE"]).ToString("dd/MM/yyy");
    

    And when you post the update, convert it to datetime in your data access method:

    SqlParameter sqlParameter1 = sqlCommand.Parameters.AddWithValue("@DeliveryDate", Convert.ToDateTime(deliveryModel.DeliveryDate));