Parsing date in Json Encoded array - javascript

I have built a MVC site and I am passing in my model to the view and attempting to use it in some javascript in the view using:
var records = #Html.Raw(Json.Encode(Model));
I am aiming on using these records in a custom calendar object that accepts an object array as a datasource. However, the datasource expects date variables to know where to put appointments etc. I've read that Json does not have any date format of it's own. So, all the dates that are returned from the encode are formatted like:
/Date(1462921200000)/
The object doesn't seem to accept this and nothing is shown on the view. In the posts that I've read they have stated that you can parse the date back into the correct format but this seems to be only on individual values.
My question is: is there an easy way to take the encoded object I've got and parse the dates into the correct format? Or would I have to loop through them in order to do it?
Thanks.

Warning: This answer is opinionated.
The opinionated part is: when you need something done with Json, use Json.Net.
namespace System.Web.MVC
{
public static class HtmlHelperJsonExtensions
{
public string JsonEncode(this System.Web.MVC.HtmlHelper html, object o)
{
var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
// Here you can apply a LOT of formatting, as a small example regarding dates:
// 1 - formats dates as iso strings (probably what you want)
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
// 2 - formats dates with Microsoft format (what you're experiencing)
//DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat,
// 3 - formats date in a custom format as for DateTime.ToString(string) overload
//DateFormatString = "yyyy-MM-dd"
Formatting = Indented
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(o, jsonSettings);
return html.Raw(json);
}
}
}
Usage:
var records = #Html.JsonEncode(Model);
Refer to the excellent Json.Net documentation here for insights.

Asp.Net MVC application return the dates in the ISO-8601 format by default.
You can convert the value in the client side with a function like this:
function ConvertDate(dateString) {
return new Date(parseInt(dateString.replace("/Date(", "").replace(")/", ""), 10));
}
Or you can use a library like momentjs (https://momentjs.com/docs/#/parsing/asp-net-json-date/):
moment("/Date(1198908717056-0700)/"); // 2007-12-28T23:11:57.056-07:00

Disclaimer: question was not identified as ASP.NET when I composed this answer. I presume the OP is asking for some feature provided by his yet to be disclosed framework. I keep the answer because I think it's valid for manual decoding in vanilla JavaScript.
The format can be parsed with a simple regular expression
var asText = "Date(1462921200000)";
var asDate = null;
var parsed = asText.match(/^Date\((\d+)\)$/);
if (parsed!==null) {
asDate = new Date(+parsed[1]);
}
console.log(asDate);

Related

get json from API: array is interpreted as a string

I have this answer from an API (written by me):
[[new Date(2017,0,28,16,00,00),[0.201766,0.201766,0.201766],[0.309878,0.309878,0.309878],[0.287467,0.287467,0.287467],[null,null,null], ...
I want my view to interpret this answer as javascript, but it doesn't. It assumes it is a string.
$.getJSON('http://localhost:XXXX/...', function (data) {
// data.jsAlignedData == [[new Date(2017,0,28,16,00,00),[0.201766,0.201766,0.201766], ...
console.log(data.jsAlignedData);
// Shows it as a string
var test = JSON.parse(data.jsAlignedData);
// Error: Unexpected token e in JSON at position 3
// (IMO it's the 'e' from 'new')
// it doesn't even reach this point:
console.log(test);
}
The final goal is to build a Dygraphs plot with a native array for increased speed (see "native array" in the documentation).
You have to serialize to date using JSON standard (see https://en.wikipedia.org/wiki/ISO_8601 for example) to be able to parse it using JSON.parse().
Edit: "JSON standard" for date type is inaccurate because you will have to interpret the date string as a JS date once parsed... (as stated in #charlietfl comment)

Validating Date Time In Javascript

I need some help with validating a date time string in Javascript, based on the browser's language.
I can get the datetime format easily enough, for instance if the language is set to pt-BR the format would be
dd/MM/yyyy HH:mm:ss
I tried using something like this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = Date.parseExact($("#theDate").val(), dateFormat);
However x is always Null. I am thinking because Date.parseExact is not able to do times. I need to be able to do this for all browser languages and I would prefer to not use another library. Using Regex is out also since I would need to write so many different expressions.
Does anyone have any suggestions to help me ge on the right track? I am also not against using a webmethod.
I have tried using the following webmethod, which works with en-US but nothing else:
Public Function ValidateDates(ByVal strDate_In As String) As String
Dim theFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern()
Try
Dim d As DateTime = DateTime.ParseExact(strDate_In, theFormat, CultureInfo.CurrentCulture)
Return "true"
Catch ex As Exception
Return "false"
End Try
End Function
You can use Regex to do this:
var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = $("#theDate").val().match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
console.log(x);
Demo: https://jsfiddle.net/kzzn6ac5/
update
The following regex may help you and improve it according to your need:
^((\d{2}|\d{4})[\/|\.|-](\d{2})[\/|\.|-](\d{4}|\d{2}) (\d{2}):(\d{2}):(\d{2}))$
It matches the following format with /.- and yyyy/mm/dd hh:mm:ss or dd/mm/yyyy hh:mm:ss
Updated demo: https://jsfiddle.net/kzzn6ac5/1 or https://regex101.com/r/aT1oL6/1
Further Regex expressions relevant to date matching can be found here.
JavaScript date objects are deceptively easy, I worked with them in a project and they had a sneaky learning-curve that takes a lot of time to master (as opposed to the rest of JavaScript, which is relative child's play). I recommend letting VB, or really anything else handle it.
But if you want a way to do it in javascript, without Regex (as stated in your question), you could perform string operations on it like this:
try {
var user_input = $("#theDate").val();
var split = user_input.split(" "); // 0: date, 1: time
var split_time = split[1].split(":"); // 0: hours, 1: minutes, 2: seconds
d.setHours(split_time[0]);
d.setMinutes(split_time[1]);
} catch {
// not in a valid format
}
This solution assumes the input is in the correct format, and if an error occurs, it's not. It's not the best way of doing things, but JS Date objects are seriously horrible.

Dojo JSON serialization, using various serialization strategies

I have the issue with serializing inputs of DateTextBox and TimeTextBox to JSON - during serialization the timezone convertion is made, which forces me to send timezone to server and do appropriate adaptations there.
To prevent there I'd like to change the date format for serialization purposes. I can alter Date's prototype, as described here (I've done that in JSFiddle), but I'd prefer not to alter the behaviour for the scope of single request. Something like that:
someDojoUtil.jsonSerialize(obj, {option1: 'value1'...})
Does Dojo provide the way for achieving it, or the only way is to globally alter Date's prototype?
Based on comment elaboration in OP, I would use the second argument to Json.stringify, the so-called "replacer". Something like this:
require(['dojo/json'], function(Json) {
function replacer(key, value) {
if ('string' === typeof (value)) {
var d = new Date(value);
if (isNaN(d.getTime())) {
return value; // string, but not a date
}
// do whatever you want to do, this is just an example
d.setSeconds(0);
return d.toJSON();
}
return value;
}
var data = {'a':new Date(), 'b':123, 'c':'foo', 'd':[new Date()]};
var str = Json.stringify(data, replacer);
console.log(str);
});
I suggest writing this as a mixin for dojo/request, then creating yourself a custom request class that has this behavior, then using that custom request object as needed.
This feels hackish, but I think it will meet your need (as I'm understanding it!).

Stringify date in javascript in valid .Net format

I have a JSON object on client side that I want to get back on server side.
To do so, I have a hidden in which I put the stringified version of my object.
$("#<%=hidden.ClientID%>").val(JSON.stringify(obj));
Then, on server side, I try to deserialize it with JavaScriptSerializer.
My Problem : the stringified object contains a date and I can't parse it with de JavaScriptSerializer.
What I have done : Modify the date format to make it fit with the .Net format :
function FormatDate(date) {
if (typeof (date.getTime) != "undefined") {
return '\\/Date(' + date.getTime() + ')\\/'
}
return date;
}
Which seems to give a good format, but, when I use JSON.stringify on the object with the well formatted dates, it adds an extra backslash, so the JavaScriptSerializer still can't get it.
Any idea on how I could get it in a valid format in the hidden?
I had the same Problem and
'\/Date(' + date.getTime() + ')\/';
works for me.
You just have a double backslash instead of only one backslash.
I use the code below to fix the data after serializing.
var data = JSON.stringify(object);
data = data.replace(/\\\\/g, "\\");
Old question but in case someone arrives here like me looking for a solution, found this that works:
https://stackoverflow.com/a/21865563/364568
function customJSONstringify(obj) {
return JSON.stringify(obj).replace(/\/Date/g, "\\\/Date").replace(/\)\//g, "\)\\\/")
}

Dash in date format and get method

I have asp (classic) script and within javascript code. From database I get date in format yyyy-mm-dd (2010-10-14) and save in variable. Then, I pass this variable to javascript method:
Response.Write("<a href='Javascript: PassDate("&OurDate&","&Val1&","&Val2&");'>Pass</a>")
This method code is:
function PassDate(OurDate, Val1, Val2)
{
window.open("newsite.asp?date="+OurDate+"&val1="+Val1+"&val2="+Val2");
}
When I try get date on new site (newsite.asp) by Request.QueryString("date"), I get calculate value 1996 (2010-10-14 = 1986), instead date '2010-10-14'.
I try various ways to solve this problem, but it still calculate value.
For example, I try replace "-" for ".", but I get error about missing ")".
Use commas instead of dashes. That way, each part will be seen as a separate argument to the JavaScript function.
Have you considered saving the date using the javascript date object and then passing that to your method?
My javascript is a little rusty, but I believe it would be something like the following:
var dateParts = split(OurDate, "-");
var myDate = new Date(dateParts[0], dateParts[1], dateParts[2]);

Categories