'Adjust for Time Zone and DST in C#

I have an Code that iterates through JSON, the date and time in the JSON is in UnixEpocSeconds UTC time.

There are two datetimepickers in my gui. Start and End Date for a query. And a selection to set the Time zone, bound to TimeZoneInfo.GetSystemTimeZones().

I'm trying to look at historical data points going back up to 10 years, and I'm being told that my output is not accounting for DST correctly. The method I'm using works for Adjusting the start time to the appropriate TZ. So if you select 12:00 01JAN2021 - 01JAN2022 EST, it'll offset all the data points -5 UTC. It does not adjust for DST. So, on March 8th @ 2AM it doesn't move the clock forward. I am able to adjust the output times to DST, but then when you select 12:00AM During DST GMT (Edinburgh, London UTC-0), it shows 1AM as the first start point.

I think I'm overthinking this, but I can't seem to put my finger on a solution.

TimeZoneInfo selectedTimeZone = (TimeZoneInfo)cbTimeZone.SelectedItem;        
//Get Start and End Date, Offset against TimeZone
TimeSpan startDate = getEpoch(dateStart.Value);
TimeSpan endDate = getEpoch(dateEnd.Value);
TimeSpan UTCOffset = new TimeSpan(selectedTimeZone.BaseUtcOffset.Hours, selectedTimeZone.BaseUtcOffset.Minutes, selectedTimeZone.BaseUtcOffset.Seconds);
startDate = startDate.Add(UTCOffset);
endDate = endDate.Add(UTCOffset);
    
//get data from API
HistData histData = APICalls.GetHistData(startDateSec, endDateSec, location);

DataRow dataPointRow;

        
foreach (var x in histData.data[0].Attributes.data_points)
{
    long time = (long)x[0];

    DateTime adjustedTime = FromUnixEpochTime(time, selectedTimeZone);
    DateTime epochTime = fromEpoch(time);
    epochTime = epochTime.Subtract(UTCOffset);
    double value;
    double.TryParse(x[1].ToString(), out value);

    //add data to table OUT range
    if (!(value >= lRange && value <= uRange))
    {
        string dataPointTime = epochTime.ToString("dd-MMM-yyyy hh:mm tt");
        string dataPointValue = String.Format("{0:0.00}", (decimal)value);

        //Update Form Datagrid View Datatable
        DataRow row = dt.NewRow();
        row[0] = dataPointTime;
        row[1] = dataPointValue;
        dt.Rows.Add(row);

        //Update Report Dataset - DataPoint Table
        dataPointRow = ds.DataPoints.NewRow();
        dataPointRow["date"] = dataPointTime;
        dataPointRow["datapoint"] = dataPointValue;
        dataPointRow["ReportID"] = 1;
        ds.DataPoints.Rows.Add(dataPointRow);

        pointsInRange++;
    }
}

Code to convert UnixEpochTimeSeconds

private TimeSpan getEpoch(DateTime date)
{
    DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan temp = date - unixEpoch;
    return temp;
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source