Convert DateTime To JSON DateTime

前端 未结 7 1084

I have a WebService which return DateTime Field.

I get a result /Date(1379048144000)/ but

i want just 1379048144000 how can i ach

相关标签:
7条回答
  • 2020-12-16 21:54

    with Json.NET :

    string date = Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now);    
    
    0 讨论(0)
  • 2020-12-16 21:59

    try regex:

    var jsonDate = @"/Date(1379048144000)/"; 
    var regex = /-?\d+/; 
    var jsonDate = re.exec(jsonDate); 
    var dateOriginal = new Date(parseInt(m[0]));
    
    0 讨论(0)
  • 2020-12-16 22:03

    U can always solve your problem when sending a date in a JSON object to JS by converting the date as follows:

    var myJSDate = (new Date(parseInt(obj.MyDate.substr(6)))).toJSON();
    

    Where obj.Date contains the date you wanna format.

    Then u'll get something like this: "2013-10-25T18:04:17.289Z"

    U can always check it in Chrome console by writing:

    (new Date()).toJSON();
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-16 22:04

    You could change your WS to return a long with the value of the DateTime. The value to return is the number of milliseconds since the Unix Epoch (01/01/1970). This could be done with an extension method on DateTime something like:

    public static class DateTimeExtensions
    {
        ...
        private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
    
        public static long ToUnixTime(this DateTime dateTime)
        {
            return (dateTime - UnixEpoch).Ticks / TimeSpan.TicksPerMillisecond;
        }
        ...
    }
    

    And your web service method might look something like:

    public long GetMyDate(...)
    {
        DateTime dateTime = ...;
        return dateTime.ToUnixTime();
    }
    
    0 讨论(0)
  • 2020-12-16 22:07

    Simply write like this to convert your date string in JSON format.

    date = "{" + date + "}";
    
    0 讨论(0)
  • 2020-12-16 22:11

    There are two solutions:

    1. client side:

    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();
    }

    It is possible to need alsou to convert into data object var date = new Date(xxx)

    1. Server side:

      Newtonsoft.Json.JsonConvert.SerializeObject(your_object)
      
    0 讨论(0)
提交回复
热议问题