ColumnMapping.DataTableToObjectList gives me DateTime properties lacking timezone information - javascript

I have a webapi function that retrieves data from a T-SQL database using SqlConnection, SqlCommand etc. I get a DataTable which I convert to a data structure using
var foobars = ColumnMapping.DataTableToObjectList<Foobar>(dt)
The Foobar class contains DateTime fields.
When I return my foobars from the webapi method, those datetimes will be sent over the network in the following format:
2016-10-12T12:00:00
which seems to be a timezone-less datetime. AngularJS will treat it as 12:00, and javascript´s Date.getHours() will return 14 (I am in the +2 timezone).
If I do this operation before I return from my Web api method:
foobar.d = foobar.d.ToUniversalTime();
the string will get an additional Z
2016-10-12T12:00:00Z
and both AngularJS and javascript will agree about which time that is (12:00, which is also the indended time).
If I do
foobar.d = foobar.d.DateStart.ToLocalTime();
the string will be
2016-10-12T14:00:00+02:00
and AngularJS and javascript both reports it is 14:00, two hours more than the intended time).
From this, I conclude that
A DateTime object can be timezoneless, but if you try to convert it, it will be treated as if it was UTC.
ColumnMapping.DataTableToObjectList creates structures where DateTime objects are timezoneless.
I do not want to "patch" every DateTime object, that would be an error source (that would involve calling ToUniversalTime() on every DateTime object).
Can I specify a locale when I call ColumnMapping.DataTableToObjectList?

In webapi you can configure your JsonFormatter to serialize your datetimes how you want:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
}
}
This way you don't have to do it for every datetime, assuming I'm understanding your issue...

Related

Issue with Date type (OBJECT or NUMBER)

I am using react-datepicker to handle date inputs and when i submit my form to my Spring-Mvc API, the date field is a javacript date object like below
And it get mapped (and saved into database with JPA/Hibernate) without problem in my spring bean
public class FooBean {
...
public Date dateStart;
With my Controller
#PostMapping(value = "/foos")
public Integer saveFoos(#RequestBody FooBean bean) {
return fooService.saveFoo(bean);
}
and the date field in the entity is mapped like this
#Temporal(TemporalType.DATE)
#Column(name = "date_os_start")
private Date dateStart;
But when i try to read the value from the database and send it to the client with the same FooBean (dto/json), the date value is a number like this :
And I got this Error
Warning: Failed prop type: Invalid prop `selected` of type `Number` supplied to `DatePicker`,
expected instance of `Date`.
How can I get date from database in the same format as JavaScript date object ?
It seems like when the date is saved to your database it's converted into a unix timestamp.
You would have to convert the unix timestamp back into a JS date object before passing it to whichever react-datepicker component you are using.
const date = new Date(1555372800000)

Why is .ToLocalTime not converting UTC time to local time?

I have code in my razor view:
#Model.DateUpdated.ToLocalTime().ToString("dd/MM/yyyy HH:mm:ss")
In my model the property is as follows:
public DateTime DateUpdated { get; set; }
This is populated from a date stored in the database as a UTC DateTime.
So when the time in the database comes back as 01/01/2018 08:00, I expect it to render in the view as 01/01/2018 09:00 as my local time (the machine I'm running this on) is UTC+1.
However, it remains as it's original time, retrieved from the database.
How can I get it to convert to the time zone of the server the application is running on?
Before you output the string I'd suggest logging the DateTimeKind of the DateUpdated field.
e.g.
Console.WriteLine(DateUpdated.Kind);
To ensure the field DateUpdated is actually UTC you can try:
DateUpdated = new DateTime(DateUpdated.Ticks, DateTimeKind.Utc);
Then when you output, the result should actually be in local time.
If the DateTimeKind of the original DateUpdated field was DateTimeKind.Local, the function .ToLocalTime() will have no effect. This can happen when you load a DateTime from an external source, e.g. Database, parsing etc.
If the .Kind property of the DateUpdated field was either UTC or Unspecified, the ToLocalTime() call should work as expected.

How to deal with local/UTC DateTime conversion in Kendo MVC Grid?

I'm getting mad with the Kendo grid. In my ASP.NET MVC project I use a database that contains archive values with a UTC datetime. I want to show these values on my page, but I need the datetime values to be shown as local (browser context) datetime. I also do have two JQuery datepickers for the start/end datetime selection of the desired range that must also work with local time. These two datepickers modify the filters of the grid on each change.
I already managed to change the filter's datetime to UTC by using this code when the datepicker's values change:
var filterExists = false;
$.each($filter, function (index, entry) {
if (entry.field == "DateValue" && entry.operator == "lte") {
entry.value = EndDate.toISOString();
filterExists = true;
console.log("UTCEndDate: " + EndDate.toISOString());
}
})
if (filterExists == false) {
$filter.push({ field: "DateValue", operator: "lte", value: EndDate.toISOString() });
}
When I look into the POST request, the start and end datetimes get send as UTC.
Now the controller fetches the data from the DB like this:
public ActionResult JournalData([DataSourceRequest]DataSourceRequest request)
{
JsonResult jsonNetResult = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
var JournalData = db.DoubleDataValueArchive.ToDataSourceResult(request, x => new JournalEventModel
{
DateValue = x.DateValue,
StationId = x.StationId,
Value = x.Value,
});
jsonNetResult.Data = JournalData;
return jsonNetResult;
}
Using this code, the data gets returned to the grid in UTC. The data is shown in the grid, but the datetimes don't match the values in the datepickers (which show the local datetime).
As I could not figure out a way to convert these datetimes to local time in the grid itself, I tried converting it to local time in the controller by using
DateValue = x.DateValue.ToLocalTime(),
in the code shown before. But now the grid's datetime filter values don't match. Now, when I want to show data for e.g. the last two hours, the most recent hour is not shown when the client's time is UTC+1. This is extremely annoying and I don't know how to resolve this issue.
As far as I can see, sending and returning datetimes to and from the server in UTC would be the most stable way. All conversion should be done on client side and not on the server. It seems that the grid can not work with UTC "under the hood" and display local time whereever it gets rendered on the page.
I hope that somebody ran into this issue before. Thanks for your help!

OData Date Filtering from JS

I am using the DXTREME framework from Devexpress to connect a HTML mobile app to an OData source.
One of my tables in SQL Server, exposed through the OData service is a table with a date (not datetime) field in it. It is exposed through OData like this:
<d:TaskDate m:type="Edm.DateTime">2010-04-01T00:00:00</d:TaskDate>
I am trying to filter the data on this field through a calendar control, but when I try to filter the datasource on the JS side, I get no matches. This is because the date is passed to the OData service, I believe, in UTC format, so if I query for TaskDate = '10/JUL/2013', I believe the date is passed as "09/JUL/2013 14:00". If I filter on TaskDate > '10/JUL/2013' I get results back from after "09/JUL/2013 14:00" at any rate.
I have tried declaring a new date with no time part:
filterDate = new Date(2013, 6, 10)
but is still doesn't work, it still subtracts 10 formy time zone on the JS side.
What I want to do is to return a lists of Tasks valid on that particular date. How can I achieve this?
I think my problem was the confusion around the dxDateBox control returning just a date, and that date being changed when passed to my odata service.
I solved the issue by converting the date to UTC myself, but just using the Date parts from the control, (where filterDate came from the control):
var paramDate = new Date(Date.UTC(this.filterDate().getFullYear(), this.filterDate().getMonth(), this.filterDate().getDate()));
this.dataSource.filter(["TaskDate", "=", paramDate]);
This works nicely, but seems rather verbose.

Pass Date object from javascript to asp.net mvc controller

I have a Date variable in client side and I want to pass the Date variable to my controller at server side.
I have passed as a normal field and the date is defaulting to 01-01-0001 12:00:00 AM.
help me to convert the date field with the right format.
ASP.NET MVC expects the DateTime value to be in the format of Thread.CurrentLanguage. Please check what language you are using.
Its like that because users might enter a Date in a TextBox and the they would enter the format of their language.
Like Pieter said: an easy way is to use a string in this case.
Another way is to use
protected void Application_BeginRequest(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
}
in Global.Asax.
You can switch back to the language of the user in a filter after the ModelBinding happend:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string language = //find a way to get the language - I have it in the route
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(language);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(language);
base.OnActionExecuting(filterContext)
}
This way has some risks, but I find it easier in lots of situations if modelBinding uses InvariantCulture (think of decimal values in the route, datetime in the route...)
I think it would be the easiest to pass the string representation of the date to the ASP.NET MVC action and attempt to parse it using DateTime.TryParse(..).
[HttpPost]
public ActionResult(string dateTimeString)
{
DateTime tempDateTime;
if(DateTime.TryParse(dateTimeString, out tempDateTime))
{
//Handle
}
}

Categories

Resources