How to convert json time to regular date/time?

I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following:

return new JsonResult(myModel); 

This works well, except for one problem. There is a date property in the model and this appears to be returned in the Json result like so:

"\/Date(1239018869048)\/" 

How should I be dealing with dates so they are returned in the format I require? Or how do I handle this format above in script?

Replay

Just to expand on casperOne's answer.

The JSON spec does not account for Date values. MS had to make a call, and the path they chose was to exploit a little trick in the javascript representation of strings: the string literal "/" is the same as "\/", and a string literal will never get serialized to "\/" (even "\/" must be mapped to "\\/").

See http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2 for a better explanation (scroll down to "From JavaScript Literals to JSON")

One of the sore points of JSON is the lack of a date/time literal. Many people are surprised and disappointed to learn this when they first encounter JSON. The simple explanation (consoling or not) for the absence of a date/time literal is that JavaScript never had one either: The support for date and time values in JavaScript is entirely provided through the Date object. Most applications using JSON as a data format, therefore, generally tend to use either a string or a number to express date and time values. If a string is used, you can generally expect it to be in the ISO 8601 format. If a number is used, instead, then the value is usually taken to mean the number of milliseconds in Universal Coordinated Time (UTC) since epoch, where epoch is defined as midnight January 1, 1970 (UTC). Again, this is a mere convention and not part of the JSON standard. If you are exchanging data with another application, you will need to check its documentation to see how it encodes date and time values within a JSON literal. For example, Microsoft's ASP.NET AJAX uses neither of the described conventions. Rather, it encodes .NET DateTime values as a JSON string, where the content of the string is /Date(ticks)/ and where ticks represents milliseconds since epoch (UTC). So November 29, 1989, 4:55:30 AM, in UTC is encoded as "\/Date(628318530718)\/".

A solution would be to just parse it out:

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));

However I've heard that there is a setting somewhere to get the serializer to output DateTime objects with the new Date(xxx) syntax. I'll try to dig that out.

Here's my solution in Javascript - very much like JPot's, but shorter (and possibly a tiny bit faster):

value = new Date(parseInt(value.substr(6)));

"value.substr(6)" takes out the "/Date(" part, and the parseInt function ignores the non-number characters that occur at the end.

EDIT: I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below. Also, please note that ISO-8601 dates are preferred over this old format -- so this format generally shouldn't be used for new development. See the excellent Json.NET library for a great alternative that serializes dates using the ISO-8601 format.

For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

There are quite a bit of answers to handle it client side, but you can change the output server side if you desired.

There are a few ways to approach this, I'll start with the basics. You'll have to subclass the JsonResult class and override the ExecuteResult method. From there you can take a few different approaches to change the serialization.

Approach 1: The default implementation uses the JsonScriptSerializer. If you take a look at the documentation, you can use the RegisterConverters method to add custom JavaScriptConverters. There are a few problems with this though: The JavaScriptConverter serializes to a dictionary, that is it takes an object and serializes to a Json dictionary. In order to make the object serialize to a string it requires a bit of hackery, see post. This particular hack will also escape the string.

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            // Use your custom JavaScriptConverter subclass here.
            serializer.RegisterConverters(new JavascriptConverter[] { new CustomConverter });

            response.Write(serializer.Serialize(Data));
        }
    }
}

Approach 2 (recommended): The second approach is to start with the overridden JsonResult and go with another Json serializer, in my case the Json.NET serializer. This doesn't require the hackery of approach 1. Here is my implementation of the JsonResult subclass:

public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();
            isoConvert.DateTimeFormat = _dateFormat;
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}

Additional credits: James Newton-King

Using jQuery to auto-convert dates with $.parseJSON

Note: this answer provides a jQuery extension that adds automatic ISO and .net date format support.

Since you're using Asp.net MVC I suspect you're using jQuery on the client side. I suggest you read this blog post that has code how to use $.parseJSON to automatically convert dates for you.

Code supports Asp.net formatted dates like the ones you mentioned as well as ISO formatted dates. All dates will be automatically formatted for you by using $.parseJSON().

Moment.js is an extensive datetime library that also supports this. http://momentjs.com/docs/#/parsing/asp-net-json-dates/

ex: moment("/Date(1198908717056-0700)/")

It might help. plunker output

I had the same problem and instead of returning the actual date value I just used ToString("dd MMM yyyy") on it. Then in my javascript I used new Date(datevalue), where datevalue may be "01 Jan 2009".

See this thread:

http://forums.asp.net/p/1038457/1441866.aspx#1441866

Basically, while the Date() format is valid javascript, it is NOT valid JSON (there is a difference). If you want the old format, you will probably have to create a facade and transform the value yourself, or find a way to get at the serializer for your type in the JsonResult and have it use a custom format for dates.

Ajax communication between the client and the server often involves data in JSON format. While JSON works well for strings, numbers and Booleans it can pose some difficulties for dates due to the way ASP.NET serializes them. As it doesn't have any special representation for dates, they are serialized as plain strings. As a solution the default serialization mechanism of ASP.NET Web Forms and MVC serializes dates in a special form - /Date(ticks)/- where ticks is the number of milliseconds since 1 January 1970.

This problem can be solved in 2 ways:

client side

Convert the received date string into a number and create a date object using the constructor of the date class with the ticks as parameter.

function ToJavaScriptDate(value) {
  var pattern = /Date\(([^)]+)\)/;
  var results = pattern.exec(value);
  var dt = new Date(parseFloat(results[1]));
  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();

}

server side

The previous solution uses a client side script to convert the date to a JavaScript Date object. You can also use server side code that serializes .NET DateTime instances in the format of your choice. To accomplish this task you need to create your own ActionResult and then serialize the data the way you want.

reference : http://www.developer.com/net/dealing-with-json-dates-in-asp.net-mvc.html

Not the most elegant way but this worked for me:

var ms = date.substring(6, date.length - 2);
var newDate = formatDate(ms);

function formatDate(ms) {

    var date = new Date(parseInt(ms));
    var hour = date.getHours();
    var mins = date.getMinutes() + '';
    var time = "AM";

    // find time
    if (hour >= 12) {
        time = "PM";
    }
    // fix hours format
    if (hour > 12) {
        hour -= 12;
    }
    else if (hour == 0) {
        hour = 12;
    }
    // fix minutes format
    if (mins.length == 1) {
        mins = "0" + mins;
    }
    // return formatted date time string
    return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + hour + ":" + mins + " " + time;
}

I have been working on a solution to this issue as none of the above answers really helped me. I am working with the jquery week calendar and needed my dates to have time zone information on the server and locally on the page. After quite a bit of digging around, I figured out a solution that may help others.

I am using asp.net 3.5, vs 2008, asp.net MVC 2, and jquery week calendar,

First, I am using a library written by Steven Levithan that helps with dealing with dates on the client side, Steven Levithan's date library. The isoUtcDateTime format is perfect for what I needed. In my jquery AJAX call I use the format function provided with the library with the isoUtcDateTime format and when the ajax call hits my action method, the datetime Kind is set to local and reflects the server time.

When I send dates to my page via AJAX, I send them as text strings by formatting the dates using "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz". This format is easily converted client side using

var myDate = new Date(myReceivedDate);

Here is my complete solution minus Steve Levithan's source, which you can download:

Controller:

public class HomeController : Controller
{
    public const string DATE_FORMAT = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public JsonResult GetData()
    {
        DateTime myDate = DateTime.Now.ToLocalTime();

        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }

    public JsonResult ReceiveData(DateTime myDate)
    {
        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }
}

Javascript:

<script type="text/javascript">

function getData() {
    $.ajax({
        url: "/Home/GetData",
        type: "POST",
        cache: "false",
        dataType: "json",
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
            sendData(newDate);
        }
    });
} 

function cleanDate(d) {
    if (typeof d == 'string') {
        return new Date(d) || Date.parse(d) || new Date(parseInt(d));
    }
    if (typeof d == 'number') {
        return new Date(d);
    }
    return d;
}

function sendData(newDate) {
    $.ajax({
        url: "/Home/ReceiveData",
        type: "POST",
        cache: "false",
        dataType: "json",
        data:
        {
            myDate: newDate.format("isoUtcDateTime")
        },
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
        }
    });
}

// bind myButton click event to call getData
$(document).ready(function() {
    $('input#myButton').bind('click', getData);
});
</script>

I hope this quick example helps out others in the same situation I was in. At this time it seems to work very well with the Microsoft JSON Serialization and keeps my dates correct across timezones.

If you doing eval("(" + jsonResult + ")") on the result, it should work. You may be best to, as mentioned, do a cusom serialization of the date/time to a client specific GMT/UTC string. Dates aren't defined within the JSON specification, but using Date(TIME_T) will work unless you are doing client-side validation of JSON responses.

Edit:example


var o = eval("({ dtm: new Date('1990/01/05') })");
alert(o.dtm);

//milliseconds from 1970-01-01 to 1990-01-05 aka TIME_T * 1000
o = eval("({ dtm: new Date(631522800000) })");
alert(o.dtm);

both work...

Format the date within the query.

var _myModel = from _m in model.ModelSearch(word)
    select new { date = ((DateTime)_m.Date).ToShortDateString() };

The only problem with this solution is that you won't get any results if ANY of the date values are null. To get around this you could either put conditional statements in your query BEFORE you select the date that ignores date nulls or you could set up a query to get all the results and then loop through all of that info using a foreach loop and assign a value to all dates that are null BEFORE you do your SELECT new.

Example of both:

var _test = from _t in adc.ItemSearchTest(word)
                        where _t.Date != null
                        select new { date = ((DateTime)_t.Date).ToShortDateString() };

The second option requires another query entirely so you can assign values to all nulls. This and the foreach loop would have to be BEFORE your query that selects the values.

var _testA = from _t in adc.ItemSearchTest(word)
                         select _i;

            foreach (var detail in _testA)
            {
                if (detail.Date== null)
                {
                    detail.Date= Convert.ToDateTime("1/1/0001");
                }
            }

Just an idea which I found easier than all of the javascript examples.

You can use this method:

String.prototype.jsonToDate = function(){
    try{
        var date;
        eval(("date = new " + this).replace(/\//g,''));
        return date;
    }
    catch(e){
        return new Date(0);
    }
};

The better way to handle dates in knockoutjs is to use moment library and handle dates like boss. You can easily deal with dates like /Date(-62135578800000)/. No need to bother of how your serialize date in controller.

function jsonToDate(date,format) {
   return moment(date).format(format);
}

use it like

var formattedDate = jsonToDate(date,'MM/DD/YYYY')

momentjs supports lots of date time formats and utility functions on dates.

I found that creating a new JsonResult and returning that is unsatisfactory - having to replace all calls to return Json(obj) with return new MyJsonResult { Data = obj } is a pain.



So I figured, why not just hijack the JsonResult using an ActionFilter:

public class JsonNetFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is JsonResult == false)
            return;

        filterContext.Result = new JsonNetResult((JsonResult)filterContext.Result);
    }

    private class JsonNetResult : JsonResult
    {
        public JsonNetResult(JsonResult jsonResult)
        {
            this.ContentEncoding = jsonResult.ContentEncoding;
            this.ContentType = jsonResult.ContentType;
            this.Data = jsonResult.Data;
            this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
            this.MaxJsonLength = jsonResult.MaxJsonLength;
            this.RecursionLimit = jsonResult.RecursionLimit;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
                && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("GET not allowed! Change JsonRequestBehavior to AllowGet.");

            var response = context.HttpContext.Response;

            response.ContentType = String.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;

            if (this.Data != null)
                response.Write(JsonConvert.SerializeObject(this.Data));
        }
    }
}



This can be applied to any method returning a JsonResult to use JSON.Net instead:

[JsonNetFilter]
public ActionResult GetJson()
{
    return Json(new { hello = new Date(2015, 03, 09) }, JsonRequestBehavior.AllowGet)
}

which will respond with

{"hello":"2015-03-09T00:00:00+00:00"}

as desired!



You can, if you don't mind calling the is comparison at every request, add this to your FilterConfig:

// ...
filters.Add(new JsonNetFilterAttribute());

and all of your JSON will now be serialized with JSON.Net instead of the built-in JavaScriptSerializer.

add jquery ui plugin in your page.

function JsonDateFormate(dateFormate, jsonDateTime) {
    return $.datepicker.formatDate(dateFormate, eval('new ' + jsonDateTime.slice(1, -1)));
};

It returns Server Date Format. You need to define your own function.

function jsonDateFormat(jsonDate) {

// Changed data format;
return (new Date(parseInt(jsonDate.substr(6)))).format("mm-dd-yyyy / h:MM tt");

};

Look into this blog entry: http://yobriefca.se/blog/2010/11/20/better-json-serialisation-for-asp-net-mvc. The author explains a solution to this date time issue in detail and uses Json.Net to write his own wrappers for a JsonResult, which uses custom date time converters.

Here's some JavaScript code I wrote which sets an <input type="date"> value from a date passed from ASP.NET MVC.

    var setDate = function (id, d) {
    if (d !== undefined && d !== null) {
        var date = new Date(parseInt(d.replace("/Date(", "").replace(")/", ""), 10));
        var day = ('0' + date.getDate()).slice(-2);
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var parsedDate = date.getFullYear() + "-" + (month) + "-" + (day);
        $(id).val(parsedDate);
    }
};

You call this function like so:

setDate('#productCommissionStartDate', data.commissionStartDate);

Where commissionStartDate is the JSON date passed by MVC.

Not for nothing, but there is another way. First, construct your LINQ query. Then, construct a query of the Enumerated result and apply whatever type of formatting works for you.

var query = from t in db.Table select new { t.DateField };
var result = from c in query.AsEnumerable() select new { c.DateField.toString("dd MMM yyy") };

I have to say, the extra step is annoying, but it works nicely.

What worked for me was to create a viewmodel that contained the date property as a string. Assigning the DateTime property from the domain model and calling the .ToString() on the date property while assigning the value to the viewmodel.

A JSON result from an MVC action method will return the date in a format compatible with the view.

View Model

public class TransactionsViewModel
{
    public string DateInitiated { get; set; }
    public string DateCompleted { get; set; }
}

Domain Model

public class Transaction{
   public DateTime? DateInitiated {get; set;}
   public DateTime? DateCompleted {get; set;}
}

Controller Action Method

public JsonResult GetTransactions(){

var transactions = _transactionsRepository.All;
        var model = new List<TransactionsViewModel>();

        foreach (var transaction in transactions)
        {
            var item = new TransactionsViewModel
            {
                ...............
                DateInitiated = transaction.DateInitiated.ToString(),
                DateCompleted = transaction.DateCompleted.ToString(),
            };

            model.Add(item);
        }
        return Json(model, JsonRequestBehavior.AllowGet);
}

Override the controllers Json/JsonResult to return JSON.Net:

This works a treat

Annoying, isn't it ?

My solution was to change my WCF service to get it to return DateTimes in a more readable (non-Microsoft) format. Notice below, the "UpdateDateOriginal", which is WCF's default format of dates, and my "UpdateDate", which is formatted to something more readable.

How to convert json time to regular date/time?

Here's how to do it:

Changing WCF date format

Hope this helps.

Category: javascript Time: 2009-04-07 Views: 5

Related post

  • How to convert timestamp / rowversion to a date and time in SQL Server? 2015-04-20

    How to convert timestamp / rowversion to a date and time in SQL Server? I have several tables where I would like to track the last update, with column names like ModifiedAt, UpdatedAt, UpdatedDate. Would this be possible if these were with a Rowversi

  • How to convert created_time filed value to date from Instagram media object 2016-02-11

    I am wokring with instagram api. My requirement is how to convert or parse date from media object respose like "created_time": "1279340983"? any idea? --------------Solutions------------- Once you have the response from the Instagram A

  • change server date time to local date time 2015-07-18

    how to change the server date time to local date time using javascript. I am using following function for getting the server time.Now i want to change this time to local time zone. function getTimeZoneAndServerDateTime() { var context = SP.ClientCont

  • How to convert JSON message into ISO 8583 2016-01-26

    I need your help. I work in Spring, and would like to know how to convert a JSON message into ISO 8583 message. Is there any other way to encrypt a JSON message? For example, I have a JSON object like this: {"id":12,"desc":"tutori

  • Convert JSON URL to R Data Frame 2016-01-31

    I'm having trouble converting a JSON file (from an API) to a data frame in R. An example is the URL http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2010&week=1&format=json I've tried a few different suggestions from S/O

  • How to convert decimal years into a date (format dd-mmm-yyyy or similar) in either Excel or SPSS? 2011-11-04

    I've found a fair number of formulas online which let me convert birthdate into decimal age in years but I can't find something that converts, for instance, 1.0 into 04-Nov-2011. Any help would be much appreciated. EDIT: Here is an example: I current

  • Converting Date/Time Text to Date/Time Values 2012-10-08

    I am having a small issue in Excel 2010, I have a column with date/time values in plain text, I wish to convert them to date/time values and add on one year. Example : 14/10/2011 03:49:00 to 14/10/2012 03:49:00 I have this working for converting the

  • How can I include SFDC object AND date-time stamp in process.outputSuccess for DataLoader? 2014-06-10

    When using the DataLoader, the default format for the process.outputSuccess file is success041214124151388.csv, ie the string 'success' plus a date-time stamp. How can I include the SFDC object (or bean id) in the file name and still keep the date-ti

  • How to convert list of stack images to time series files in R 2014-10-29

    I am using bfast package for time series analysis. But it requires the files to be read as time series. How to convert list of stacked images from 2000 to 2013 into a time series and given as input for analysis? --------------Solutions------------- Y

  • How can we apply filter in view for a content type by start date-time and end date-time? 2015-01-28

    I want to show the latest exam on a tablet based notice board. I am using Drupal 7. For this I need to show an item from a content type called Exams which has a start date and end date with time. After the time ends I need to show the next item if th

  • Workflow - How to convert string to number to date? 2015-07-27

    I have a string strExpDate and I get the value "130836384000000000" from ldap query. The active directory field is accountExpires. I need to convert this to date/time. The result should be 8/9/2015 7:00:00 PM. I tried convert this string to numb

  • How to convert any formatted text box date to DateTime(YYYY-mm-dd)format 2016-01-16

    I am working with date function.data comes in different format like 1."2016-01-31" 2."31-01-2016" 3."31/01/2016" 4."2016/01/31" 5."jan 01 2016" 6."2016-01-02 12:00 AM" Now I want to convert all a

  • how to convert json file to csv using java? 2016-02-10

    Could anyone provide example for converting jsonfile to csv using java please. Does anyone having code to convert json to csv, here whenever i give json its automatically convert into csv using java please? --------------Solutions------------- First,

  • How can I add PDT (Pacific Daylight Time) to the Date&Time panel 2012-05-08

    I would like to add PDT to the list of locations in the Date & Time panel. I have UTC, so I think that in general, abstract locations are working. But when trying to add PDT, I only get this unresponsive stop-icon. SO: is there a way to add PDT to th

  • How to convert multidimensional matrix into regular matrix? 2014-03-14

    I have this multidimensional matrix: {{{{a1, a2}, {a3, a4}}, {{b1, b2}, {b3, b4}}}, {{{c1, c2}, {c3, c4}}, {{d1, d2}, {d3, d4}}}} I would like to convert it into this regular matrix: {{a1, a2, b1, b2}, {a3, a4, b3, b4}, {c1, c2, d1, d2}, {c3, c4, d3,

  • How to convert string to number or date in angularjs expression 2014-09-04

    I am using angularjs to make a pagination type of thing, say I have a 2D array and I am displaying the values from it. Its working fine but I also want to be able to edit thoes values so I used ng-hide in input tag and its working fine but the proble

  • How to use JSON result as the data input for GraphView? 2016-01-14

    This is what it returned from the .php url. [[{"date0":"2016-01-20","sgrcon0":"48"},{"date1":"2016-01-13","sgrcon1":"56"},{"date2":"2016-01-04","sgrco

  • How can I convert a local date-time into UTC date-time? 2015-09-03

    I am trying to get a bash script working and in order to do so I need to transform a local time in +%Y%m%d%H%M%S format (example: "20150903170731") into UTC time in the same format. I know date -u can give me the current UTC time: $ date +%Y%m%d

  • How to convert JSON/xml data to any other readable format 2016-01-19

    url = 'https://maps.googleapis.com/maps/api/place/radarsearch/json?location=%.7f,%.7f&radius=500&types=food|cafe&keyword=vegetarian&key=API_KEY'%(latitude,longitude) resp = urllib.urlopen(url) a =resp.read() print a How can I read output o

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 2.763 (s). 13 q(s)