Change the UTC DateTime received from the server to the Local DateTime displayed on the web page

In my Sql database, I have a column storing values as UTC in a DateTime field. The requirement now is to convert this UTC into Local Time based on the geographical location of the User accessing the report.

I am aware that using ToLocalTime() will achieve the conversion but it would be to the server's location where the application is deployed, and not the User's Geo location.

This is the code snippet I am currently using:

<td>@string.Format("{0:yyyy-MMM-dd HH:mm:ss}", user.StatusDateTime.ToLocalTime())</td>

My interface uses Razor View along with javascript/jquery. What could be a feasible solution to address this issue?

Answer №1

Alright, one way to approach this is by passing the date to the view (without calling .ToLocalTime()), and then leveraging JavaScript to display it in the local timezone using the provided link.

<script>document.write(new Date('@user.StatusDateTime.ToString("yyyy-MM-dd hh:mm:ss UTC")').toString());</script>

Take note of

.ToString("yyyy-MM-dd hh:mm:ss UTC")
for compatibility with JavaScript (there might be more efficient methods).

Update:

If you require a specific date format (e.g. 2015-Dec-22 12:11:38), you can create a custom JavaScript function. Below is an illustration.

function getFormattedLocalDate(utcDateString) {
    var date = new Date(utcDateString);
    var months = [
      "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
    var formattedDate = date.getFullYear() + '-' + months[date.getMonth()] + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    return formattedDate;
}

View it live.

Update 2:

Check out an example usage within an html table here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to loop through a nested object and extract values into an array?

I'm currently working on extracting data points from an API response to use in graphing. My goal is to extract an array of the "4. close" values from the object below. let res = { "Meta Data": { "1. Information": "Daily Prices (open, hig ...

my javascript loop simultaneously activates all twelve data attributes in one go

In my attempt to create a music playlist program, I encountered an issue with triggering each song independently. The script I wrote only seems to work when there is one song in the HTML file. When I added 12 songs and organized them using data attributes, ...

What is the reason for not being able to locate the controller of the necessary directive within AngularJS?

A couple of angularjs directives were written, with one being nested inside the other. Here are the scripts for the directives: module.directive('foo', [ '$log', function($log) { return { restrict: 'E', r ...

Exploring the world with HTML5 Geolocation on Google Maps

I've recently been studying a tutorial on HTML5 geolocation and I'm looking to make some modifications to the code. Specifically, I want to add a text input for the destination address instead of having a fixed destination. Any suggestions or met ...

The incorrect z-index value for a triangle in Three JS is causing a visual distortion

I recently ran into an issue while working with Three.js that I need help with. Here is the problem I encountered: After doing some research, it seems like this is a CanvasRenderer problem. Is there a way to resolve this without switching to WebGLR ...

Best practices for using Promises in NodeJS

I'm in the process of developing a library that builds on top of amqp.node (amqplib), focusing on simplifying RabbitMQ functionality for our specific project needs. This new library is designed to utilize Promises. So, for instance, when subscribing ...

Experience the power of CanJS Observable data objects with the added feature of

When working with canJS Observable, I encountered an issue where I cannot use dots in object keys because canJS interprets them as nesting. For example, if I try to create a new observable like this: var obs = new can.Observe( { "div.test-class": { "color ...

Responsive menu not collapsing properly and appearing funky in Drupal

I've managed to create a responsive navigation bar, but I'm encountering two issues. Firstly, when I resize the screen on my test pages, not all of the links hide as expected. Secondly, after inserting the code into Drupal, the nested links appea ...

Understanding the ContentAlignment enum valuesExplanation of ContentAlignment enum values

Here is the System.Drawing.ContentAlignment enum: namespace System.Drawing { // Summary: // Describes the alignment of content on the drawing surface. [Editor("System.Drawing.Design.ContentAlignmentEditor, System.Drawing.Design, Version=4. ...

Guide to setting up a click event for a group of input items, specifically radio buttons

I am looking to trigger some JavaScript code whenever a user clicks on any of the radio buttons in my web application. Despite my efforts, I am having trouble capturing a click event on the list of input elements. Currently, in my app, I have included the ...

Embedding version 8: navigating a basic class

After following the example in the V8 embedder's guide for "Accessing Dynamic Variables," I have successfully adjusted the code to compile with the newest version. However, the example only demonstrates how to define accessors for a Class. If I want t ...

What is the redirect URL for the OAuth2 REST API in a .NET Standard class?

I am in the process of developing a .NET Standard class designed to handle connection information for publicly available REST APIs. Since this class is intended to be used by various front-end applications, some of which may not have a "redirect URL" to ca ...

What is the best way to save a beloved pet for a user who is signed in?

Is there a way to store a favorite pet for a logged-in user using React and Express? I am currently retrieving pets from an API and using PostgreSQL as the database. const favPetDetails = { id, name, media, breeds, location, dista ...

JavaScript's failure to properly handle UTF-8 encoding

Here is a snippet of code that I found on Stack Overflow and modified: <?php header('Content-Type: text/html; charset=ISO-8859-1'); $origadd = $_SESSION["OriginAdd"] // $_SESSION["OriginAdd"] contains the value "rueFrédéricMistral"; echo $o ...

Here is a unique rewrite of the text: "Learn the process of toggling the tabindex for

Is there a way to dynamically change the tabindex of an element based on its visibility in the viewport? I am looking to either reset the current tabindex when entering a new section and assign new values to elements within that section, or disable and re- ...

Is it possible to include a base url for imports in React JS?

Conventional method for adding imports: import Sample from ‘../../../components/signup’ I want to simplify imports by removing the front dots and slashes: import Component from ‘components/signup’ Is there a way to set a base URL for imports to ...

What are the steps for defining the maximum and minimum values in AngularJS?

I'm working with the following HTML markup: <div class="input-group-icon">Max <span class="error">*</span> <div class="input-group"> <input style="border-right:none;" name="available_funds_max" ng-model="attributes.avai ...

Avoid duplicating content when using Ajax to retrieve data in jQuery

Is there a solution when you click the button to display content, then click the button to hide it, and then click the button again to show it repeatedly? I'm not sure how to solve this issue. Can anyone help me out? Thank you! Here is the HTML code: ...

Does the [data-empty] constitute a component of the browser environment?

While exploring a node.js project that employs socket.io, I came across a piece of code that verifies whether the length of $('[data-empty]') is larger than 0. There was no class or ID associated with it, but it seemed like data-empty was some ki ...

The node.js oauth-1.0a implementation is successful in authenticating with Twitter API v1.1, however, it encounters issues

Having come across this function for generating an oauth-1.0a header: // auth.js const crypto = require("crypto"); const OAuth1a = require("oauth-1.0a"); function auth(request) { const oauth = new OAuth1a({ consumer: { key ...