Question: Get local datetime instead of server DateTime in server side code C#

Question

Get local datetime instead of server DateTime in server side code C#

Answers 4
Added at 2016-12-26 19:12
Tags
Question

I am using ASP MVC 4.5. I have view to input payment details. I use C# to get current time when user input payment. But after hosting it on server, i found a hot error. It gets another dateTime (may be my server's time) instead of my user's local time! I want to get user's current time using C#. Should i use C# or javascript? I think it is easy to get user's time using javascript. But i want to use C# for this. Can you help me? My web API:

 // POST api/PaymentApi
    public HttpResponseMessage PostPayment(Payment payment)
    {
        if (ModelState.IsValid)
        {
           var mem= db.Members.Where(m => m.MemberID.Equals(payment.MemberID)).FirstOrDefault();

           if (mem ==null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }


           payment.Date = DateTime.Now;
            db.Payments.Add(payment);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, payment);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = payment.PaymentID }));
            return response;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }

I used payment.Date = DateTime.Now.ToLocalTime(); also but not worked!

Many of here answered to use javascript date. That's why i used it. But javascript sends a datetime and my WebApi makes it slightly different.
Javascript: Date:Tue Dec 27 2016 11:04:12 GMT+0600 (Local Standard Time) C#: Date:{27/12/2016 05:04:12} enter image description here

Answers to

Get local datetime instead of server DateTime in server side code C#

nr: #1 dodano: 2016-12-26 19:12

DateTime works with local host's clock, e.g. the server. Most payments systems save the dates as relative to UTC, to avoid client/server time differences.

payment.Date = DateTime.UtcNow;
nr: #2 dodano: 2016-12-26 20:12

It's impossible to get client DateTime at server-side if client is not sending it by itself.

nr: #3 dodano: 2016-12-26 20:12

There isn't any way to know the user Local time from the server. What you need to do is send the local time from the client to the server inside the request in UTC format.

Javascript(requires Jquery):

var UTC = new Date().getTime();
nr: #4 dodano: 2016-12-26 20:12

You'll need to get the local date time in javascript and pass it to the server. I recommend you to use ISO8601 format.

Source Show
◀ Wstecz