Home > Enterprise >  Convert Int to date C#
Convert Int to date C#

Time:10-03

I feel like this should be pretty easy, but I am having a hard time figuring it out. I am getting a int from an API for a date. The Json provides the date property like this "20210307". What is the best way for me to get this date into into yyyy/mm/dd format and is there a way to also flip things around (maybe put year last?). I have been trying to make a method in the class but only run into problems and it is making me think I am totally off. Thanks!

    List<CovidDataModel> coviddata;
    string errorString;

    protected override async Task OnInitializedAsync()
    {
        var request = new HttpRequestMessage(HttpMethod.Get, "https://api.covidtracking.com/v1/states/daily.json");

        var client = _clientFactory.CreateClient();

        HttpResponseMessage response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            coviddata = await response.Content.ReadFromJsonAsync<List<CovidDataModel>>();
            errorString = null;
        }
        else
        {
            errorString = $"Could not load Covid Data: {response.ReasonPhrase}";
        }
    }

PORTION OF MODEL BELOW:

public class CovidDataModel
    {
        public int date { get; set; }
    }

CodePudding user response:

You can use DateTime.ParseExact to parse custom date formats. Simply switch "yyyyMMdd" accordingly to the int date response you are receiving.

int date = 20210307;

var dateTime = DateTime.ParseExact(
    date.ToString(), 
    "yyyyMMdd", 
    CultureInfo.InvariantCulture);

Console.WriteLine(dateTime);

Output:

7/3/2021 12:00:00 AM

CodePudding user response:

Assuming that your date integer is in yyyymmdd format:

int date = 20210307;

int year = date / 10_000;
int month = (date - year * 10_000) / 100; 
int day = date % 100;

DateTime dateTime = new DateTime(year, month, day);

Once you have your DateTime you can format it how you like using normal date formatting.

(You can also do it by converting the integer to a string and then parsing it, but obviously that's a lot less efficient - not that that's likely to matter...)

CodePudding user response:

You don't need to parse the string to an int. If you already receive it as a string you can use DateTime.TryParseExact() to parse it like this:

using System;
using System.Globalization;
                    
public class Program
{
    public static void Main()
    {
        var myDate = "20220901";
        
        DateTime result;        
        DateTime.TryParseExact(myDate, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
        
        var newDateFormat = result.ToString("yyyy/MM/dd");
        
        Console.WriteLine(newDateFormat);
    }
}

This will give you: "2022/09/01"

You can "flip the things around" by specifying the format string:

//put year last (Day/Month/Year):
var newDateFormat = result.ToString("dd/MM/yyyy");

This will give you: "01/09/2022"

CodePudding user response:

int sampleDate = 20210307;
var dateFormat = DateTime.ParseExact(sampleDate.ToString(), "yyyyMMdd",
         CultureInfo.InvariantCulture).ToString("yyyy/MM/dd");

result:

"2021/03/07"

  • Related