Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user's local sytem's datetime in asp.net mvc?

Tags:

asp.net-mvc

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?

like image 682
Gaurav Pandey Avatar asked Sep 16 '10 06:09

Gaurav Pandey


3 Answers

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

like image 74
Justin Avatar answered Oct 24 '22 01:10

Justin


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.

like image 29
Jon S. Avatar answered Oct 23 '22 23:10

Jon S.


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.

like image 36
this. __curious_geek Avatar answered Oct 24 '22 00:10

this. __curious_geek