Is there any way to get the date January 1, 1970 Greenwich Mean Time in a datetime?
if i just specify new date(1970, 1, 1) i will get it with my current time zone..
Is there any way to get the date January 1, 1970 Greenwich Mean Time in a datetime?
if i just specify new date(1970, 1, 1) i will get it with my current time zone..
GMT is, for all practical purposes, the same as UTC.
This means that you can just use one of the DateTime
constructors that takes a DateTimeKind
parameter, setting it to DateTimeKind.Utc
.
DateTime gmt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
Check out the DateTimeOffset
structure
EDIT: Actually, after further reading about DateTimeOffset
, it might not be the most adequate solution for what you're trying to do... I think this is the most direct answer to your question :
DateTime epoch = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
GMT is equal to UTC (Coordinated Universal Time), more or less (unless you're dealing with fractions of seconds, there's no difference). DateTimeKind, an enumeration which lets you choose whether to display time in your local time zone or in UTC, is built into the DateTime constructor. Using this, we can achieve the equivalent of GMT.
The constructor we're looking to use is the following:
DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
or (in one there is a millisecond argument, in the other there isn't):
DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)
To obtain a DateTime for January 1, 1970 in UTC, this is what we can use:
DateTime inGMT = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); //using 1st constructor above
or:
DateTime inGMT = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); //using 2nd constructor above
NOTE: The contents of the enumeration DateTimeKind are below:
UPDATE: Thomas Levesque proposed a very creative solution in his answer, however I'm not sure if it is the most direct method and if it's a viable method that can be used for any time zone. What I think he's saying is that you can calculate the DateTimeOffset from DateTime.Now and DateTime.UtcNow, and apply the calculated offset to January 1, 1970 in your own time zone, which gives you it in UTC/GMT time. I'm not sure that there are simple methods to calculating offsets to other time zones, and then this becomes a bit redundant to the question.
UPDATE #2: I added another DateTime constructor which accomplishes the same thing, but lacks the millisecond argument. They are interchangable.