-2
{"meritSystemCalendar":{"businessDate":"2021-04-21T00: 00: 00","cycleCode":"D"},"responseCode":"ok","statusCode":200}

On parsing the BusinessdDate into a DateTime property, the value stored is "21-04-2021 00:00:00"

How to convert the property to "4/21/2020" in c#

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
MainakChoudhury
  • 502
  • 1
  • 7
  • 23
  • 5
    Does this answer your question? [Specifying a custom DateTime format when serializing with Json.Net](https://stackoverflow.com/questions/18635599/specifying-a-custom-datetime-format-when-serializing-with-json-net) – Yong Shun Apr 22 '21 at 06:33
  • 2
    What is the real problem> The value is **not stored** as `"21-04-2021 00:00:00"`. `Datetime` has no format, it's a binary value just like `byte` or `int`. It actually stores an Int64 tick count internally. Formats only apply when parsing a string into a DataTime, or formatting a DateTime into a string for display – Panagiotis Kanavos Apr 22 '21 at 06:39
  • 2
    I didn't downvote but there must be at least 3 identical questions each week. A simple search would find them. – Panagiotis Kanavos Apr 22 '21 at 06:41
  • 1
    Does this answer your question? [Getting Date or Time only from a DateTime Object](https://stackoverflow.com/questions/4097127/getting-date-or-time-only-from-a-datetime-object) – Naveed Hematmal Apr 22 '21 at 07:13
  • When you convert a Strng to datetime the format will depend on the settings in your machine. There is nothing wrong. If you want a different format than you have to change the settings in VS to display the DateTime to a different culture. – jdweng Apr 22 '21 at 07:16

1 Answers1

0

There are multiple methods to extract the date from the DateTime variable.

First: You can use the [DataType(DataType.Date)] annotation above the DateTime property in your model.

Second: You can use ToString() method to capture the date from the DateTime variable.

The code snippet for the second method is below.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ExportDTtoJSON
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> p = new List<Person>();
            p.Add(new Person
            {
                FirstName = "Ahmad",
                DOB = new DateTime(2021, 1, 1).ToString("yyyy/mm/dd")
            });
            p.Add(new Person
            {
                FirstName = "Khan",
                DOB = new DateTime(2022, 3, 4).ToString("yyyy/mm/dd")
             });

            var jsonObject = Newtonsoft.Json.JsonConvert.SerializeObject(p);
        }
    }

    public class Person
    {
        public string FirstName { get; set; }
        public string DOB { get; set; }
    }
}

jsonObject has the JSON data, and you can apply your logic to that.

Naveed Hematmal
  • 343
  • 4
  • 17