Consuming JSON dates in a EXTJs gridpanel - c#

I have a object that im serializing to a JSON object using JSON.Net. This object is then being consumed by a JSON Store which is attached to a ExtJs GridPanel.
All fields except date fields render fine , the only way i can render date fields is if i use text columns. But then i get the following /Date(1293746400000+0200)/ rendered as text which is useless.
I know i need to convert that somehow to a proper date object but i have not idea how atm.
Let me know if you need more info.

"M$" in the preceeding example is misleading, its "MS". Here is a clear example that works in extjs 4. The 'LastFellOffCliff' field is set to be a date with incoming format in the Microsoft JSON date style: "/Date(...)/"
Ext.define('ACME.model.CoyoteModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'CoyoteID', type: 'int' },
'Nickname',
{ name: 'LastFellOffCliff', type: 'date', dateFormat: 'MS' },
'Notes'
]
});

JSON.Net has various date/time converters to help you deal with this. See this blog post for some details. So you could use the JavaScriptDateTimeConverter for example, then eval the result into a JS date object. I can't recall off the top of my head how an Ext store will deal with that, but maybe it will point you in the right direction.

Have a look at here.
In most cases you can pass your own formatted string (i use "yyyy-MM-dd" in my projects as i don't need time) and re-use it on the other side (format it as a valid date constructor).

In the field(s) that is/are for the date in your JsonStore, you can set the field's type to 'date' and its dateFormat to 'M$'. Works like a champ.

Related

JSON parse DateTime

From the server I get this string
[{\"id\":\"9b77ff1e-350e-44d8-8860-15e80f4d8a22\",\"code\":\"C\",\"name\":\"0%\",\"validFrom\":\"2013-07-01T00:00:00Z\",\"validTill\":null,\"active\":1,\"vatProc\":0.0,\"createdAt\":\"2015-02-01T13:04:17.733Z\",\"updatedAt\":\"2015-02-01T13:04:17.733Z\"}]
On the client side I then convert it to a json object using JSON.parse which produces the result:
[
{
active:1
code:"C"
createdAt:"2015-02-01T13:04:17.733Z"
id:"9b77ff1e-350e-44d8-8860-15e80f4d8a22"
name:"0%"
updatedAt:"2015-02-01T13:04:17.733Z"
validFrom:"2013-07-01T00:00:00Z"
validTill:null
vatProc:0
}
]
Which is as you would expect if it where not for the date fields.
The dates are on server translated to UTC.
I know I can pass a function to parse the function to do the conversion.
I would just like to format the date's so that the regular parse would do it "right" if you know what I mean
I saw on the net that there is no "right" way and that every case what I was reading about on the net is working with conversion on the client side.
So is there really no way to tell the regular json parser that that is a date?
I have the option to convert that date-time to what ever would work on the server
ClientSide: AngularJS
ServerSide: C# WCF / json
EDIT:
The problem that I am having is that if I use for instance the ValidFrom as a model in AngularJS it is complaining that it is not a date witch it really is not
AngularJS error:
Expected `2013-07-01T00:00:00Z` to be a date
Before I send a date to the client I set the DateTimeKind property to utc
SomeObject.Date= DateTime.SpecifyKind(SomeObject.Date, DateTimeKind.Utc);
Before saving any date to the server I do:
SomeObject.Date= SomeObject.Date.ToUniversalTime();
The only requirement on the client is to use momentjs format() method in order to convert the date to ISO-8601
Following this method JSON always handles times correctly on the client (at least it has worked fine so far for me)
This helped me a lot

German culture - get double number from JSON with a comma

I have an MVC Web-API application for inner use. I have some pages with forms and numeric fields. I need to install this on a German computer, and the users will be only Germans. In Germany they write "3,5" instead of "3.5" (with a comma).
In IIS configuration the culture is "Invariant culture" and since the computer is German - the localize is "de-DE".
When the users write "3,5" in the field - I can see in firebug that "3,5" is what is sent in JSON, but the server gets it as "35".
Can I handle it on server-side? (I don't want to change the json because I'll need to do it in every field and page)
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class ItemsController : ApiController, IDisposable
{
[Authorize(Roles = "Admin")]
[HttpPost]
public HttpResponseMessage UpdateItem(ItemViewModel itemVM)
{
// JSON data sent data.NumProp1 = "3,5"
// itemVM.NumProp1 contains "35" instead of "3.5"
}
}
You should not localize your JSON - see http://www.json.org for the spec (which only shows the dot as a separator) and How to localize when JSON-serializing? for a similar question.
I wouldn't recommend trying to read your customized JSON - it may sound like a quick win right now, but in the end you simply aren't using JSON.
You must use CultureInfo.InvariantCulture on all your string formating calls when handling persitence (and JSON exchanges are technically a form of persitence):
Persisting Data
The InvariantCulture property can be used to persist data in a
culture-independent format. This provides a known format that does not
change and that can be used to serialize and deserialize data across
cultures. After the data is deserialized, it can be formatted
appropriately based on the cultural conventions of the current user.
For example, if you choose to persist date and time data in string
form, you can pass the InvariantCulture object to the
DateTime.ToString(String, IFormatProvider) or
DateTimeOffset.ToString(IFormatProvider) method to create the string,
and you can pass the InvariantCulture object to the
DateTime.Parse(String, IFormatProvider) or
DateTimeOffset.Parse(String, IFormatProvider, DateTimeStyles) method
to convert the string back to a date and time value. This technique
ensures that the underlying date and time values do not change when
the data is read or written by users from different cultures.
This applies to all types: numerics, decimals, floats and doubles, date and time etc. Use the invariant culture both when writing and when reading serialized data. Use invariant culture on both sides of a JSON exchange.
BTW, if you'd use the built-in JSON serializers, you'd already get this lunch for free: JsonWriter.cs, JsonReader.cs.
As already said: JSON is a standard, and you should never deviate from the standard. Doing that will make your life miserable.
If the users enter some numbers in a web form, that web form should serialize that in the correct JSON format. I think usually that is done already, if you use the right numeric types in your form, like input type='number', etc. On the server end, you should read it using the InvariantCulture.
This need for a general solution is acknowledged by the W3C, as you can see in the draft W3C HTML JSON form submission.
In addition to the other answers, if you want to just replace the German "," decimal separator with the current culture one, which makes the conversion parse correctly, use:
str = str.Replace(",", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
You can then convert your string into a numeric value using stuff like Convert.ToInt32

how to convert unknown format according to my system culture info?

How do I convert an anonymous date format to my own system culture info?
I am using a jquery calendar .datepicker(), but when I'm trying to get the value of that text box in the c# datetime variable, it shows invalid date time string. I have tried datetime.tryparse ,datetime.parse,convert.todatetime() and many others.
Now I am trying to get the date in jquery like var a = date.now();
But I am getting the following error: date.prototype //invalid date
I don't know why this is happening.
Reading your comments (" i am also getting error in prototype= invalid date and when i am trying to using this var a to set the date in another calendar"), I think you're trying to set calendars within jquery, possibly within an asp.net page.
If this is the case, you can set the date format when you create the datepicker :
$( ".calendar" ).datepicker({ dateFormat: "mm-dd-yyyy" }); // 10-25-2013
Format it as you need. For a list of date formatting options, see http://api.jqueryui.com/datepicker/#utility-formatDate.
If this doesn't help, it would be useful to know :
* what is emitting the date
* what is consuming the date (jquery/ C#)
* the actual code that is generating errors, if any.
After reading your responses, I think you should try specifying the format of your datepicker explicitly.

Get vs Post Auto Mapping dates C#

I am having some confusion figuring out why I am experiencing the following:
If I using jquery AJAX to "post" some Json data containing a date to an MVC controller the automapper maps the date in the format dd/mm/yyyy however if I use "get" instead the automapper seems to convert the date in to the format mm/dd/yyyy.
Does anybody know why this would be the case? When I check the json payload and querystrings for the post and get respectively they are both in the same format. The date I am using goes across as "1/7/2013" in both cases.
Regards,
Gary
Are you using a JSON serializer for the POST but a DateTime.Parse for the GET? This could yield two different results.
User DateTime.ParseExact to ensure consistent results. I.E.
DateTime.ParseExact(input, "dd/MM/yyyy HH:mm", null);

Datetime formats and JSON data in C#

I'm having an issue with date/time formats in ASP.NET/C#. I have my SQL Server database set up with a PostDate field set to a type of "datetime". But it's saving the date in a strange format. I added a new row through a form and I got this as the date/time string:
2012-09-28 14:56:48.910
When it gets parsed by JSON.NET it gets even stranger. I get:
2012-09-28T14:56:48.91
The date and time are obviously correct, but how do I set things so that I can parse the date into a human-friendly way? There isn't really any code to post because the date is being added when the row is inserted. I'd like to format this as "Sept. 28, 2012 2:56 pm". How do I do that? Do I need to format the string before or after it's parsed as JSON?
That's not a "strange" format at all. The second form is ISO-8601; the first is ISO-8601 without the T. Considering the strange formats you can get in JSON, it looks like you've been let off pretty lightly!
Serialization formats aren't meant to be user-friendly, particularly - they're meant to be machine-to-machine formats.
I would hope that JSON.NET would give you a DateTime after parsing; it should only be giving you the ISO-8601 format after you've converted back to JSON.
If you've got a DateTime that you want to format for user consumption, there are all kinds of options with standard and custom format strings. Don't forget that you should respect the culture of the user, as far as possible - so make sure you're taking appropriate steps to either set the thread's current culture to be the user's one, or that you're passing the culture explicitly to DateTime.ToString etc.
You can try it in C#:
.ToString("MMM d yyyy, h:mm tt")

Categories

Resources