Converting .Net Datetime to JSON

Converting .NET DateTime to JSON

What is returned is milliseconds since epoch. You could do:

var d = new Date();
d.setTime(1245398693390);
document.write(d);

On how to format the date exactly as you want, see full Date reference at http://www.w3schools.com/jsref/jsref_obj_date.asp

You could strip the non-digits by either parsing the integer (as suggested here):

var date = new Date(parseInt(jsonDate.substr(6)));

Or applying the following regular expression (from Tominator in the comments):

var jsonDate = jqueryCall();  // returns "/Date(1245398693390)/"; 
var re = /-?\d+/;
var m = re.exec(jsonDate);
var d = new Date(parseInt(m[0]));

Convert DateTime To JSON DateTime

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

Specifying a custom DateTime format when serializing with Json.Net

You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter, then specify the date format in the constructor of the subclass. Apply the JsonConverter attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:

class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd";
}
}

If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK (as seen in the source code).

How to Convert .NET DateTime to JSON

You can ignore the time zone offset - the number of milliseconds is always relative to UTC (see the "DateTime wire format" section at http://msdn.microsoft.com/en-us/library/bb412170.aspx). The offset mostly indicates that the original DateTime value was of DateTimeKind.Local, but the serialized milliseconds since the epoch is always relative to GMT.

JSON Date and DateTime serialisation in c# & newtonsoft

As I mentioned in a comment, there is no standard date representation in JSON. The ISO8601 is the de-facto standard, ie most people started using this some years ago. ISO8601 does not require milliseconds. If the other endpoint requires them, it's violating the defacto standard.

Json.NET has been using IOS8601 since version 4.5. The current one is 10.0.3. The following code :

JsonConvert.SerializeObject(DateTime.Now)

returns

"2017-09-08T19:01:55.714942+03:00"

On my machine. Notice the timezone offset. That's also part of the standard. Z means UTC.

You can specify your own time format, provided it's the correct one. In this case, it should be yyyy-MM-ddTHH:mm:ss.fffZ. Notice the fff for milliseconds and HH for 24-hour.

The following code

var settings=new JsonSerializerSettings{DateFormatString ="yyyy-MM-ddTHH:mm:ss.fffZ"};
var json=JsonConvert.SerializeObject(DateTime.Now,settings);

returns

"2017-09-08T19:04:14.480Z"

The format string does not force a timezone translation. You can tell Json.NET to treat the time as Local or Utc through the DateTimeZoneHandling setting :

var settings=new JsonSerializerSettings{
DateFormatString ="yyyy-MM-ddTH:mm:ss.fffZ",
DateTimeZoneHandling=DateTimeZoneHandling.Utc};
var json=JsonConvert.SerializeObject(DateTime.Now,settings);

Returns :

"2017-09-08T16:08:19.290Z"

UPDATE

As Matt Johnson explains, Z is just a literal, while K generates either Z or an offset, depending on the DateTimeZoneHandling setting.

The format string yyyy-MM-ddTH:mm:ss.fffK with DateTimeZoneHandling.Utc :

var settings=new JsonSerializerSettings{
DateFormatString ="yyyy-MM-ddTH:mm:ss.fffK",
DateTimeZoneHandling=DateTimeZoneHandling.Utc};
var json=JsonConvert.SerializeObject(DateTime.Now,settings);

Will return :

2017-09-11T9:10:08.293Z

Changing to DateTimeZoneHandling.Utc will return

2017-09-11T12:15:12.862+03:00

Which, by the way is the default behaviour of Json.NET, apart from the forced millisecond precision.

Finally, .NET doesn't have a Date-only type yet. DateTime is used for both dates and date+time values. You can get the date part of a DateTime with the DateTime.Date property. You can retrieve the current date with DateTime.Today.

Time of day is represented by the Timespan type. You can extract the time of day from a DateTime value with DateTime.TimeOfDay. Timespan isn't strictly a time-of-day type as it can represent more than 24 hours.

What was that yet?

Support for explicit Date, TimeOfDay is comming through the CoreFX Lab project. This contains "experimental" features that are extremely likely to appear in the .NET Runtime like UTF8 support, Date, String, Channles. Some of these already appear as separate NuGet packages.

One can use the System.Time classes already, either by copying the code or adding them through the experimental NuGet source

Convert Date into JSON object in c#

double ticks = Math.Floor(objRemarkData.Date.ToUniversalTime() 
.Subtract(new DateTime(1970, 1, 1))
.TotalMilliseconds);
var newob = new { Date =ticks, Remark = objRemarkData.Remark};
JS.GetJSON(newob);

.NET Core - converting date of read JSON file

If you need to deserialize date in different formats, you have to create a custom JsonConverter:

public class MultiFormatDateTimeConverter : JsonConverter
{
private List<string> formats;

public MultiFormatDateTimeConverter(List<string> formats)
{
this.formats = formats;
}

public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string dateString = (string)reader.Value;

foreach (string format in formats)
{
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date))
{
return date;
}
}
throw new JsonException("Unable to parse \"" + dateString + "\" as a date.");
}

public override bool CanWrite
{
get { return false; }
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

Usage example:

var settings = new JsonSerializerSettings();
settings.DateParseHandling = DateParseHandling.None;
settings.Converters.Add(new MultiFormatDateTimeConverter(new List<string> { "DD-MM-YYYY hh:ss", "YYYY-MM-DDThh:mm:ss" }));

userObjects = JsonConvert.DeserializeObject<List<UserImportModel>>(content, settings);

C# convert datetime to WCF datetime format

Since you asked how to serialize with this format using JSON.NET:

// Set the DateFormatHandling wherever you are configuring JSON.Net.
// This is usually globally configured per application.
var settings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};

// When you serialize, DateTime and DateTimeOffset values will be in this format.
string json = JsonConvert.SerializeObject(yourDateTimeValue, settings);

However, I highly recommend you do NOT use this format unless you absolutely have to, usually for purposes of compatibility with old code. The ISO-8601 format is preferred (de facto) format for dates and times in JSON.

See also: On the nightmare that is JSON Dates.



Related Topics



Leave a reply



Submit