A
A
Alexander Prokopenko2022-01-31 14:51:54
C++ / C#
Alexander Prokopenko, 2022-01-31 14:51:54

How to convert unix to datetime c#?

Good afternoon, I want to make a graph with data, but I have time in unix, when I convert it, an error is generated. Here is my code:

// Пример: 44443.8340277778 это дни от 1900 года, я от них отнимаю 70 лет и в секунды
string[] lines = File.ReadAllLines(directory + @"\newData.dat");

for (int j = 0; j < lines.Length - 1; j += 4)
{
    try
    {
        long unix = (long)TimeSpan.FromDays(long.Parse(lines[j]) - 2550).TotalSeconds;

        DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(unix);
        DateTime utc = dateTimeOffset.UtcDateTime;

        dates.Add(utc.ToString("yyyy-MM-dd-HH-mm"));
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

chart1.AxisX.Clear();
chart1.AxisX.Add(new Axis()
{
    Title = "Время",
    Labels = dates
});


Mistake:
61f7ceef405b2559685322.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Voland69, 2022-01-31
@AlexanderProkopenko

There is only one Parse in your block, and the error seems to be in it.
If the example is correct, then I see two errors:

  1. long cannot parse a real number
  2. if you take double with the default Russian locale, it will not be able to either - because decimal separator is wrong

PS the calculation method is doubtful - what is 2550 in days? If 70 years is 25550 days excluding leap years (70*365).
PPS DateTime can store from January 1, 0001, its AddDays accepts Double, I think that your algorithm can be simplified and generally get rid of unix time seconds.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question