Date and Time Zone Management in MVC

馋奶兔 提交于 2020-05-16 03:24:26

问题


I am confused about the correct method to use culture invariant in c# , On hosting the application there seems some error with date and time i included <globalization uiCulture="en-IN" culture="en-IN" /> and everything works fine . But on migration to cloud Elastic Beanstalk the Application failed again So i included <globalization uiCulture="en-IN" culture="en-IN" /> Again but failed in other time zones expect indian The date selected using datepicker is passed to controller using ajax code pass it to stored procedure for database operation that how application works ! but the date enter in database seems wrong (01-01-0001). what is the correct method to handle datetime ? which will work for all timezone ? i tried taking current culture and that method didnt worked since my query is not about the code wise error i am not adding any code

    public JsonResult CreateAcademicInfo(CreateCommand create)
    {
            return Json(_academicInfo.CreateClass(create),JsonRequestBehavior.AllowGet); 


} .// controller



private bool CreateAcademicInfo(CreateCommand createAcademicInfo, IDbUtility dbObj)
        {

                ISumDbCommand cmdcreateAcademicInfo =
                    dbObj.CreateCommand("uspAddInformations", CommandType.StoredProcedure);
                cmdcreateAcademicInfo.AddParameter("HierarchyStructureName", SumDbType.String,
                    createAcademicInfo.HierarchyStructureName);
                 cmdcreateAcademicInfo.AddParameter("MaximumCount",SumDbType.Integer,createAcademicInfo.MaximumCount);
                cmdcreateAcademicInfo.AddParameter("StartDate",SumDbType.DateTime,createAcademicInfo.StartDate);
                cmdcreateAcademicInfo.AddParameter("EndDate",SumDbType.DateTime, createAcademicInfo.EndDate);
                int errorCode = dbObj.StoredProcExecute(cmdcreateAcademicInfo.DbCommand);
                if (errorCode != 0)
                {
                    throw new Exception.DbOperationException($"Error {errorCode} occurred = {dbObj.LastError}");
                }
                return true;


        } //API 

回答1:


There is not enough information to give you an answer specific to your code, but here are the outlines:

  • Convert all dates to UTC before saving them into the database.
  • Convert all dates back to local time when you fetch them from the database for display.

Now keep in mind that local time means the time in the user's zone, so ONLY the code running on the client side is the one that's aware of the local time of the user. Your .Net code runs on the server and does NOT know the local time of the user. There are ways to get the time zone of the user on the server, but it is not always reliable so better use JavaScript on the client side. That means:

  • All dates in the database must be in UTC.
  • All dates in your .Net code must be in UTC.
  • No conversion of dates is done in .Net.
  • All dates for display are in local time.
  • All conversion of dates must be done in JavaScript.
  • All date transfers between client side and server side must be in the same format, and recommended to be a universal standard format.

Now, understanding all of that, here are practical points (my recipe):

  • When you need to generate the current date on the server to be saved in the database, use DateTime.UtcNow. This is required for dates that are not coming from the client. For example, if you want to record the operation time. I prefer to do this in the app, but if you prefer to do it directly in the database, use a the database function that generates the current time in UTC.

  • I recommend using the sortable date & time format, because both JavaScript and .Net understand it. However, there is a little difference. JavaScript adds Z at the end, but that's easy to remedy. For example, 2009-06-15T13:45:30 in .Net will be 2009-06-15T13:45:30Z in JavaScript.

  • When you want to send the UTC date from .Net to JavaScript, use:

var date = new Date("@mydate.ToString("s")Z");

JavaScript will automatically convert it to local time. Beautiful, isn't it?

  • When you want to send the local date from JavaScript to .Net, use .toJSON() method. It will format it using the sortable date & time format and automatically convert it to UTC. Thing of beauty. And then, in .Net you can use one of the DateTime functions to parse the string (e.g. DateTime.Parse()).



回答2:


I was running into similar datetime related issues and this is what helped me, in your Global.asax:-

protected void Application_Start()
{
    CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
    newCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
    newCulture.DateTimeFormat.DateSeparator = "/";
    Thread.CurrentThread.CurrentCulture = newCulture;
}

protected void Application_BeginRequest()
{
    CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
    newCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
    newCulture.DateTimeFormat.DateSeparator = "/";
    Thread.CurrentThread.CurrentCulture = newCulture;
}

this will centrally set the datetime format and culture of your appliaction and also, set your datetime picker's format centrally as well with jquery and make it equal to the format you have in Global.asax



来源:https://stackoverflow.com/questions/48556149/date-and-time-zone-management-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!