How to parse PHP Doctrine Querybuilder DateTime from a HTTPResponseMessage to C# DateTime?

406

I am trying to pass a SQL result from my PHP-made website to my C# APP that I'm making with Xamarin Forms. I've done this by making A REST API endpoint in my PHP application and therefore calling the URL through my C# app. This returns a Json Array with my results. However, I can't find any way to parse the datetime object that I'm receiving to c# datetime as it has ".00000" behind the datetime that i can't get rid of.

SQL

$query = $this->createQueryBuilder('c')
     ->select('partial c.{id, image, title,contentType, createdOn }', 'partial cd.{id, data}', 'partial u.{id, email} ', 'partial ud.{id, screenName, profileImage} ')
            ->join('c.data', 'cd')
            ->join('c.user', 'u')
            ->join('u.data', 'ud')
            ->andWhere('c.user !=:user')
            ->setParameters(
                array(
                    'user' => $this->janVanAllemanId
                )
            )
            ->orderBy('c.modifiedOn', 'DESC')
            ->setFirstResult($offset)
            ->setMaxResults($limit)
            ->getQuery();

    $results = $query->getArrayResult();

JSON Array

        {
    "posts": [
        {
            "id": 3373,
            "contentType": 6,
            "createdOn": {
                "date": "2019-05-21 14:00:14.000000",
                "timezone_type": 3,
                "timezone": "Europe/Amsterdam"
            },
            ...

        },
        {
            "id": 3371,
            "contentType": 6,
            "createdOn": {
                "date": "2019-05-18 14:30:09.000000",
                "timezone_type": 3,
                "timezone": "Europe/Amsterdam"
            },
            ...

        }
    ]
}

As you can see it returns an array with "date", "timezone" and "timezone_type". I can not use this to parse it to a C# DateTime object for the life of me.

This is what I've tried:

PostRepository.cs

 public class PostRepository : Repository
    {
        public async Task<List<Post>> GetNotifications(int userId, int offset = 0, int limit = 16)
        {
            string[] queryParams = { "userId=" + userId, "offset=" + offset, "limit=" + limit };
            string uri =
RestService.GetApiUrl(UrlExtension.POST_NOTIFICATIONS, queryParams);

            List<Post> posts = new List<Post>();
            HttpResponseMessage response = null;
            response = await client.GetAsync(uri);

            if (response.IsSuccessStatusCode)
            {

                PostList postList = await response.Content.ReadAsAsync<PostList>();

                posts = postList.Posts;
            }

            return posts as List<Post>;
        }
}

PostList.cs

public class PostList
    {
        [JsonProperty("posts")]
        public List<Post> Posts { get; set; }
        public PostList()
        {
        }
    }

*Method 1: Through a DateTime property, I tried to deserialize the result.

Post.cs

...
public class Post
{
     [JsonProperty("createdOn")]
     public DateTime CreatedOnDateTime{get;set;}
}

This obviously does not work, because it's not a valid Datetime object. So I tried a JObject and getting the "date" key that you could see above in my Json array:

Post.cs

         ...


public class Post
            {
                 public DateTime CreatedOnDateTime {get;set;}
                 [JsonProperty("createdOn")]
                 public JObject CreatedOn{
                 set{  
                 CreatedOnDateTime= DateTime.ParseExact(value["date"].ToString(),
"M/d/yyyy hh:mm",CultureInfo.CreateSpecificCulture("nl-NL"));

                 }
            }

It succesfully converts to a JObject, but it generates an exception saying that it's not a valid string to convert to a datetime object! I mainly think the reason why this doesn't work is because of the .00000 that magically is appearing behind my dates?!

Anyone knows a way to convert my Json results to a C# DateTime? I really appreciate your help!

271

Answer

Solution:

You can use this one:
CreatedOnDateTime = DateTime.Parse(value["date"].ToString(), CultureInfo.CreateSpecificCulture("nl-NL"));

People are also looking for solutions to the problem: javascript - Upload files to Google Cloud Storage Bucket using PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.