Attached is a method I am currently using that takes in a list of DateTime
strings, their input format (i.e. yyyy-MM-dd HH:mm:ss
), and their offset in the form of hours.
As for the culture and "standard", I am using InvariantCulture
and I am converting the times to UTC
.
public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider);
int unixTime = (Int32)(result.ToUniversalTime().AddHours(hours).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalSeconds;
return unixTime;
}
Two issues with said method:
- I am using this website as a comparison. If my input is
2014-03-18 21:00:00
, my output, according to my method, is1395190800
, which converts back to2014-03-19 01:00:00
. It has a four hour difference. The desired output is this:
- If my input is
2014-03-18 24:00:00
, I get this error:
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
Noticeably, it does not allow the input of 24
in the HH
part. This is a weird error as NodaTime
handles it just fine... Though that's irrelevant as I am using DateTime
.
Does anyone have any insight on this area?
EDIT:
Upon some experimentation, removing the .ToUniversalTime()
removes my 4-hour offset.. Why is this happening?
public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider);
int unixTime = (Int32)(result.AddHours(hours).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalSeconds;
return unixTime;
}