2

I am building a web app with c# and angular to store event schedule. The user will input a date time which is in UTC and I want to save that time in db exactly as inputted. And then show exactly same time when a user will view this information. And this should not depend on user's timezone, and I am telling the user that time is in UTC.

But the problem is browser send time information with timezone info when ajax post to server and server saves a different time (by converting its own timezone) in db as the server is in a different timezone.

How to prevent this?

Iman Bahrampour
  • 6,180
  • 2
  • 41
  • 64
Zakir Hossain
  • 108
  • 1
  • 6

3 Answers3

4

If you are using .Net Web API as backend, you can config the timezone in Web API WebApiconfig.cs like below. It will serialize the time in UTC.

public static void Register(HttpConfiguration config)
{
    config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
}
Daniël Tulp
  • 1,745
  • 2
  • 22
  • 51
Samuel Shyu
  • 151
  • 6
  • Or use config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.RoundtripKind; //Time zone information should be preserved when converting. – Samuel Shyu Nov 15 '17 at 13:29
3

I am not sure how you are formatting. But I think you could use momentjs in case you don't want to use any custom solution. The following code should work

moment(your_date_time).format('YYYY-MM-DD HH:mm:ss')

in case your_date_time has time zone, then the following should work

moment().utc().format('YYYY-MM-DD HH:mm:ss')

Sohel
  • 431
  • 3
  • 10
  • Yes moment with first format did work there. Actually a given string format without timezone info rather than date time object are workable there. And this same thing are applicable too when i sending back time information from server to client. Need to send a specific string format rather than date time object. Thanks. – Zakir Hossain Nov 19 '17 at 05:10
2

So if you are using html5 datetime,then you can change it to datetime-local

<input type="datetime-local">

This will give you datetime without the timezone info.

Here is an example.

var dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = '2017-06-01T08:30';

let btn = document.getElementById('btns');
let inp = document.getElementById('party');
let dv = document.getElementById('displayValue');
btn.addEventListener('click', ()=>{
  dv.innerText = inp.value;
});
<label for="party">Enter a date and time for your party booking:</label>
<input id="party" type="datetime-local" name="partydate" value="2017-06-01T08:30">

<button type="submit" id="btns">Check Value</button>

<div id="displayValue">
  
</div>

Code snippet is just to give you an idea on how to use datetime-local. If you are using angular 2/4, then you can directly bind ngModel to a variable as you would do generally to get the value.

Karthik RP
  • 1,028
  • 16
  • 26