How to serialize dates with JavaScriptSerializer - c#

I'm trying to use JavaScriptSerializer to store/retrieve a date. However, I'm not getting the same value back.
Here's is the test code
var serializer = new JavaScriptSerializer();
var date = new DateTime(1997, 1, 27, 0, 0, 0, DateTimeKind.Local);
var obj = new Dictionary<string, object> { { "theDate", date } };
var json = serializer.Serialize(obj);
var obj2 = serializer.DeserializeObject(json) as Dictionary<string, object>;
var date2 = (DateTime)obj2["theDate"];
var result = date == date2 ? "success" : "failure";
The date I get back is DateTimeKind.Utc instead of DateTimeKind.Local so the result is 'failure'. What am I doing wrong?
Thanks

"JavaScriptSerializer" Can't really be trusted for anything as complex as a date. I recommend picking your favourite date format and storing the date as a string. Or, for more precision, convert it to an epoch and store that number :)

Related

convert datetime passed into parameter to a string c#

I would like to convert a datetime passed into parameter into a string using this function but it doesn't work. Could anyone help me ? Thank you in advance
Here is my function
public string ConvertDateTimeToString(DateTime date)
{
string date_str = date.ToString("dd/MM/yyyy HH:mm:ss");
return date_str;
}
and after when i create a new dateTime object
DateTime dateTest = new DateTime(2008, 5, 1, 8, 30, 52);
ConvertDateTimeToString(dateTest);
Console.WriteLine(dateTest); /// show this {01/05/2008 08:30:52}
The "ConvertDateTimeToString" will create a new string.
The existing DateTime still untouched.
You have to use the new string in your Console.WriteLine :
var dateString = ConvertDateTimeToString(dateTest);
Console.WriteLine(dateString);

Can't parse JSON data to .NET DateTime

It's pretty simple. I have a string
string s = "/Date(1474408920000)/"
And I want to convert it to a date:
DateTime date = JsonConvert.DeserializeObject<DateTime>(s);
But I get the error:
"Error parsing comment. Expected: *, got D. Path '', line 1, position 1."
What's going on here?
Thanks for your help!
Your json string is not valid but can easily be fixed by surrounding it with "
string s = #"""/Date(1474408920000)/""";
Now DateTime date = JsonConvert.DeserializeObject<DateTime>(s); will work
var LogDate = new DateTime(2016, 9, 20, 22, 2, 0, DateTimeKind.Utc);
string JsonDate = JsonConvert.SerializeObject(LogDate, new JsonSerializerSettings {
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});
Console.WriteLine(JsonDate);
Console.ReadLine();
Output from this code gives you a proper JSON date format:
"\/Date(1474408920000)\/"
So your string should look like this:
string s = "\"\\/Date(1474408920000)\\/\"";
try serializing the DateTime obj to JSON using below code.
var dateTime = DateTime.Now;
var jsonDate = Newtonsoft.Json.JsonConvert.SerializeObject(dateTime,
new Newtonsoft.Json.JsonSerializerSettings() {
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat,
DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime });
jsonDate would hold this value "\"\\/Date(1474408920000)\\/\"" or something in this format.
Now deserialize your json date string using below code.
var dateObj = Newtonsoft.Json.JsonConvert.DeserializeObject<DateTime>(dateString,
new Newtonsoft.Json.JsonSerializerSettings() {
DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTime,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat });

Parsing a DateTime value in the SyndicationFeed

I'm using below code for parsing an atom feed:
using(var reader = new MyXmlReader("http://tutsplus.com/courses.atom")) {
var doc = SyndicationFeed.Load(reader);
var newFeed = new AtomFeed {
Id = doc.Id,
Title = doc.Title.Text,
Url = url,
UpdateDate = DateTime.Now
};
XNamespace dc = "http://www.w3.org/2005/Atom";
newFeed.AtomEntries = (from entry in doc.Items
select new AtomEntry {
Id = entry.Id,
Links = entry.Links,
Title = entry.Title.Text,
Content = entry.Content.ToString(),
PublishDate = entry.PublishDate.DateTime,
UpdatedDate = entry.LastUpdatedTime.DateTime,
Authors = entry.Authors
}).ToList();
}
Seems that a string was not recognized as a valid DateTime in my feed. I'm also aware (+) that The SyndicationFeed.Load method expects to receive feeds that are in standard format like this: Mon, 05 Oct 2015 08:00:06 GMT. So I created my custom XML reader that recognizes different date formats. But still have same error!
Any idea?
When I tried it, with your linked custom XML reader, I also got this error when it came to parsing the "published" and "updated" dates. Looking at the code for the Atom10FeedFormatter class, it is trying to parse dates in these formats (DateFromString method)
const string Rfc3339LocalDateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz";
const string Rfc3339UTCDateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
http://reflector.webtropy.com/default.aspx/WCF/WCF/3#5#30729#1/untmp/Orcas/SP/ndp/cdf/src/NetFx35/System#ServiceModel#Web/System/ServiceModel/Syndication/Atom10FeedFormatter#cs/2/Atom10FeedFormatter#cs
So I changed in the MyXmlReader implementation to set that format yyyy-MM-ddTHH:mm:ssZ, then all is well with this date parsing (I also had to change in ReadStartElement the element names to set readingDate equal to true, i.e. published and updated).
public override string ReadString()
{
if (readingDate)
{
string dateString = base.ReadString();
DateTime dt;
if (!DateTime.TryParse(dateString, out dt))
dt = DateTime.ParseExact(dateString, CustomUtcDateTimeFormat, CultureInfo.InvariantCulture);
return dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
}
else
{
return base.ReadString();
}
}

Convert string value to date from FormCollection

I get new Date(2012,9,3) from FormCollection["eventDate"]
how can I get this value in DateTime variable?
string input = "new Date(2012,9,3)";
var dateTimeString = input.Split(new[] {'(', ')'},
StringSplitOptions.RemoveEmptyEntries)
.Last();
var datetime = DateTime.ParseExact(dateTimeString,
"yyyy,M,d", CultureInfo.InvariantCulture);
One way would be like this:
// new Date(2012,9,3)
var dateVals = s.Substring(9).Replace(")", "").Split(",");
var d = new DateTime(
Convert.ToInt32(dateVals[0]),
Convert.ToInt32(dateVals[2]),
Convert.ToInt32(dateVals[1]));

How do I convert DateTime .NET datatype to W3C XML DateTime data type string and back?

I have a System.DateTime object and I need to convert it into a string storing that datetime in W3C XML DateTime format (yyyy-mm-ddThh:mm:ssZ) and then be able to convert the resulting string back into System.DateTime.
Is there something ready for that in .NET or do I have to implement it myself?
I thought W3C dateTime had a lot more significant digits for the time.
Here's what I use:
// DateTime to W3C dateTime string
string formatString= "yyyy-MM-ddTHH:mm:ss.fffffffzzz";
dateTimeField.ToString(formatString) ;
// W3C dateTime string to DateTime
System.Globalization.CultureInfo cInfo= new System.Globalization.CultureInfo("en-US", true);
dateTimeField= System.DateTime.ParseExact(stringValue, formatString, cInfo);
If you want a date in the W3C XML format, then use .Net's W3C XML formatting API (been there since before v1.0):
var w3cStringFormat = XmlConvert.ToString(DateTime.Now);
results in:
2014-09-12T16:03:22.6833035+01:00
Then to get it back again:
var dateTime = XmlConvert.ToDateTime(w3cStringFormat);
This will convert to the string you need and parse back the string to the DateTime:
var now = DateTime.Now;
Console.WriteLine(now.ToUniversalTime().ToString());
var nowString = now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
Console.WriteLine(nowString);
var nowAgain = DateTime.ParseExact(nowString, "yyyy-MM-ddTHH:mm:ssZ", null);
Console.WriteLine(nowAgain.ToUniversalTime().ToString());
Console.ReadLine();
I would think JSON.net can handle it.
Use IsoDateTimeConverter.
From documentation:
public class LogEntry
{
public string Details { get; set; }
public DateTime LogDate { get; set; }
}
[Test]
public void WriteJsonDates()
{
LogEntry entry = new LogEntry
{
LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
Details = "Application started."
};
string defaultJson = JsonConvert.SerializeObject(entry);
// {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
// {"Details":"Application started.","LogDate":new Date(1234656000000)}
string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}
}
Xml Serialization is there for you. Below is the code how to:-
DateTime someDateTime = DateTime.Now.AddDays(5);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(DateTime));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
// converting to w3c xml
ser.Serialize(ms, someDateTime);
//**Edited**
ms.Position = 0;
//**Edited**
System.IO.StreamReader sr = new System.IO.StreamReader(ms);
string w3cxml = sr.ReadToEnd();
sr.Close();
ms.Close();
// doing reverse
System.IO.StringReader reader = new System.IO.StringReader(w3cxml);
DateTime thatDateTime = (DateTime)ser.Deserialize(reader);
reader.Close();

Categories