Reputation: 1840
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}
Upvotes: 2
Views: 4054
Reputation: 365
You'll need to get the local date time in javascript and pass it to the server. I recommend you to use ISO8601 format.
Upvotes: 1
Reputation: 91
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();
Upvotes: 0
Reputation: 3380
It's impossible to get client DateTime
at server-side if client is not sending it by itself.
Upvotes: 1
Reputation: 35477
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;
Upvotes: 0