Click here to Skip to main content
15,850,685 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to convert UTC date time to local so any on ecan operate app then it will take their local time but it should be global dont have to cange in all pages
Posted

1 solution

There is method for doing this in DateTime class itself, see the next example:
C#
DateTime utcDate1 = date1.ToUniversalTime(); //This is an UTC date!
DateTime date2 = utcDate1.ToLocalTime(); // And now is converted to local date!


This solution works on windows desktop application, but not in the case of web application when the clients could be from any country and your code run on the server. So in this second case you should see the next link and you have to use Javascript in you web page:
http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp[^]
 
Share this answer
 
v2
Comments
Member 9579525 27-Mar-14 3:25am    
i have to change in all page instead i want global solution which convert UTC to localtime
Raul Iloc 27-Mar-14 3:46am    
You are using MVC, so you could do the change only in your layout (master page)!
Member 9579525 27-Mar-14 7:36am    
i have written fun in layout.cshtml and calling that where i want display date but it is giving invalid date
//function

<script type="text/javascript">

$(function () {

var d = new Date()
var offsetms = d.getTimezoneOffset();// * 60 * 1000;

$('.UTCTime').each(function () {

try {

var text = $(this).html();

var n = new Date(text);
alert(n);//invalid date
n = new Date(n.valueOf() - offsetms);
n = new Date(n - offsetms);

$(this).html(n.toDateString("MM/dd/yyyy") + " " + n.toLocaleTimeString("hh:mm tt"));

$(this).attr("Converted from UTC " + text);
}
catch (ex) {

console.warn("Error converting time", ex);
}
});
});

</script>

//in cshtml
<td class="UTCTime"> @Model.date.ToString("MM/dd/yyyy, hh:mm tt")
</td>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900