I have this method that takes in a string such as 2014-03-10T08:00:00
and converts it to a unix number like this: 1394456400
Below is said method:
public string convertToUnix(string dateString)
{
string format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
format = "yyyy-MM-dd'T'HH:mm:ss";
result = DateTime.ParseExact(dateString, format, provider);
return (result - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds.ToString();
}
My format
variable is the condition for those DateTimes
that do not have timezone offsets.
My code works perfectly for the above format, but I am interested in converting numbers that have an offset which is the timezone, such as:
2014-03-10T08:00:00-07:00
The new method need not check for both conditions -- just the input with offset is fine.
I have looked at these threads such as:
I have also tried: format = "yyyy-MM-dd'T'HH:mm:ss-HH:mm";
as my condition, but I don't think this works because it requires an addition or subtraction of the offset.
EDIT:
On self-experimentation and Jon's comment of using DateTimeOffset
, I came up with this:
public static double convertToUnix2(string dateString)
{
var dateTimeOffset = DateTimeOffset.Parse(dateString, null);
return (dateTimeOffset - new DateTime(1970, 1, 1)).TotalSeconds;
}
On an input of 2014-03-10T08:00:00-07:00
, it outputs 1394445600
.
I also have this which indicates the parse is successful:
public static string convertToUnix3(string dateString)
{
var dateTimeOffset = DateTimeOffset.Parse(dateString, null);
return dateTimeOffset.ToString();
}
Input of 2014-03-10T08:00:00-07:00
and outputs 3/10/2014 8:00:00 AM -07:00
.
Is the logic of taking the DateTime
object and subtracting it from the Epoch time a correct approach?