[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Converting Newtonsoft.Json.Linq.JToken to a DateTime

Posted on 2016-10-24
4
Medium Priority
?
713 Views
Last Modified: 2016-10-24
I've got some Twitter data that looks like this:

? jsonDat[x]["created_at"].ToString()
"Mon Oct 24 07:32:25 +0000 2016"

But I'm having trouble converting it to a C# DateTime.

Here are some things I've tried and the responses.

? DateTime.Parse("Mon Oct 24 07:32:25 +0000 2016")
'DateTime.Parse("Mon Oct 24 07:32:25 +0000 2016")' threw an exception of type 'System.FormatException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233033
    HelpLink: null
    InnerException: null
    Message: "String was not recognized as a valid DateTime."
    Source: "mscorlib"
    StackTrace: "   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)\r\n   at System.DateTime.Parse(String s)"
    TargetSite: {System.DateTime Parse(System.String, System.Globalization.DateTimeFormatInfo, System.Globalization.DateTimeStyles)}

--

? System.Convert.ChangeType(jsonDat[x]["created_at"].ToString(),typeof(DateTime))
'System.Convert.ChangeType(jsonDat[x]["created_at"].ToString(),typeof(DateTime))' threw an exception of type 'System.FormatException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233033
    HelpLink: null
    InnerException: null
    Message: "String was not recognized as a valid DateTime."
    Source: "mscorlib"
    StackTrace: "   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)\r\n   at System.Convert.ToDateTime(String value, IFormatProvider provider)\r\n   at System.String.System.IConvertible.ToDateTime(IFormatProvider provider)\r\n   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)\r\n   at System.Convert.ChangeType(Object value, Type conversionType)"
    TargetSite: {System.DateTime Parse(System.String, System.Globalization.DateTimeFormatInfo, System.Globalization.DateTimeStyles)}

--

? jsonDat[x]["created_at"].ToObject<DateTime>();
'jsonDat[x]["created_at"].ToObject<DateTime>()' threw an exception of type 'System.FormatException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233033
    HelpLink: null
    InnerException: null
    Message: "String was not recognized as a valid DateTime."
    Source: "mscorlib"
    StackTrace: "   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)\r\n   at System.Convert.ToDateTime(String value, IFormatProvider provider)\r\n   at System.String.System.IConvertible.ToDateTime(IFormatProvider provider)\r\n   at System.Convert.ToDateTime(Object value, IFormatProvider provider)\r\n   at Newtonsoft.Json.Linq.JToken.op_Explicit(JToken value)\r\n   at Newtonsoft.Json.Linq.JToken.ToObject(Type objectType)\r\n   at Newtonsoft.Json.Linq.JToken.ToObject[T]()"
    TargetSite: {System.DateTime Parse(System.String, System.Globalization.DateTimeFormatInfo, System.Globalization.DateTimeStyles)}

Open in new window


It could be because I'm in the UK and the DateTime format is different - any suggestions on how I can extract a DateTime out of this value?
0
Comment
Question by:purplesoup
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 34

Accepted Solution

by:
it_saige earned 2000 total points
ID: 41857190
You want to use ParseExact or TryParseExact and specify the format which is -
ddd MMM dd hh:mm:ss zzzz yyyy

Open in new window


Custom Date and Time Format Strings - https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Proof of concept -
using System;
using System.Globalization;
using System.Threading;

namespace EE_Q28978446
{
	class Program
	{
		const string result = "Mon Oct 24 07:32:25 +0000 2016";

		static void Main(string[] args)
		{
			DateTime converted1 = default(DateTime);
			DateTime converted2 = default(DateTime);

			Console.WriteLine("Using ParseExact:");
			try
			{
				converted1 = DateTime.ParseExact(result, "ddd MMM dd hh:mm:ss zzzz yyyy", Thread.CurrentThread.CurrentCulture);
				Console.WriteLine("Successfully converted - {0}; to {1}", result, converted1);
			}
			catch (Exception)
			{
				Console.WriteLine("Error in conversion");
			}

			Console.WriteLine();
			Console.WriteLine("Using TryParseExact:");
			if (DateTime.TryParseExact(result, "ddd MMM dd hh:mm:ss zzzz yyyy", Thread.CurrentThread.CurrentCulture, DateTimeStyles.None, out converted2))
				Console.WriteLine("Successfully converted - {0}; to {1}", result, converted2);
			else
				Console.WriteLine("Error in conversion");

			Console.ReadLine();
		}
	}
}

Open in new window

Produces the following output -Capture.JPG
-saige-
1
 

Author Closing Comment

by:purplesoup
ID: 41857328
Thanks - excellent answer, I love answers with a proof of concept!
0
 

Author Comment

by:purplesoup
ID: 41857330
I had to modify it - but you weren't to know it was 24 hour clock.

? DateTime.ParseExact("Mon Oct 24 17:02:54 +0000 2016","ddd MMM dd HH:mm:ss zzzz yyyy", Thread.CurrentThread.CurrentCulture);
{24/10/2016 18:02:54}
    Date: {24/10/2016 00:00:00}
    Day: 24
    DayOfWeek: Monday
    DayOfYear: 298
    Hour: 18
    Kind: Local
    Millisecond: 0
    Minute: 2
    Month: 10
    Second: 54
    Ticks: 636129289740000000
    TimeOfDay: {18:02:54}
    Year: 2016
0
 
LVL 34

Expert Comment

by:it_saige
ID: 41857359
The lack of an AM/PM designator should be an indicator that this was needed in 24-hr format and I apologize for missing that.  Otherwise, I am glad to have been of assistance.

-saige-
1

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
A great marketing strategy is diverse.  Read about the not so popular, yet effective, marketing tactics you can start using today!
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question