I want to get the date and time of user's local system.
How can I accomplish that in a controller in ASP.NET MVC?
I think that you need to capture it via JavaScript and then send it back to the server (eg. using AJAX).
In the JavaScript: var d = new Date()
will capture what you need.
http://www.w3schools.com/js/js_obj_date.asp
This was my solution:
Note: Requires jQuery.
In the Head of the _Layout file (or all _Layout files if there are multiple), after the jQuery declarations, put:
@if (Session["UTCOffset"] == null)
{
<script type="text/javascript">
$.post('/Home/SetUTC', { UTC: new Date().getTimezoneOffset() }, function (data) { location.reload(); });
</script>
}
In the Home controller (or whatever controller you use), put:
public JsonResult SetUTC(int UTC)
{
Session["UTCOffset"] = (-1*UTC).ToString();
return Json(null);
}
When printing out date times, use (in this example DateTime.Now):
(DateTime.Now).ToUniversalTime().AddMinutes(double.Parse((string)Session["UTCOffset"]??"-300.00")).ToString("MM-dd-yyyy")
-300 is central time (my time zone). If there are any dates on the very first page they hit, they will be displayed in central time. For about a second. Then the page will be reloaded and things should work as expected.
I'm sure this could be somehow adapted for non-MVC setups but I'll leave that for somebody else.
There's no way you can do that in server-side asp.net mvc code.
Either you prompt the user with DtropDown list of all timezones and let him pick it from the list and second option is to capture local system time in client-javascript and send it to server over an AJAX request or a post-back.
In fact there's one more way - You can capture the IP of the user's machine and find out the country to which that IP belongs to and pick the TimeZone of that country. You can use MaxMind GeoIP database which can help you do this very easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With