Shinykirby
04-08-2009, 05:41 PM
I have a few functions to get the time of a timezone in C#. When I first started looking for (built-in) methods to get a unix timestamp, I found there was none, and for actual timezones, there wasn't any except for a popular library of classes that I didn't need.
Anyway, here's what I have.
private int getOffset(int timezone) {
return timezone*60*60*1000;
}
private DateTime changeZone(int offset) {
return System.TimeZone.CurrentTimeZone.ToUniversalTime
(DateTime.Now).AddMilliseconds(offset);
}
private double getUnix(DateTime dt, int offset) {
DateTime date = System.TimeZone.CurrentTimeZone.ToUniversalTime
(dt).AddMilliseconds(offset);
TimeSpan ts = date - new DateTime(1970,1,1,0,0,0);
double unixTime = ts.TotalMilliseconds;
return unixTime;
}
private DateTime getDateFromUnix(double unix) {
DateTime date = new DateTime(1970,1,1,0,0,0).AddMilliseconds(unix);
return date;
}
The way it would work is you would set getOffset to the timezone you're working with (such as -7 would be for PST) and you would run it through the other functions to get the desired result.
The question I have is, will it work? I don't have .NET on the machine I'm using right now so I can't test that myself. Works great for EST, though.
Also, some questions about the Unix timestamp. Is it measured in milliseconds? I'm not sure if I should be returning the seconds or milliseconds with it.
Last question:
Is System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now) the same as DateTime.UtcNow?
Anyway, here's what I have.
private int getOffset(int timezone) {
return timezone*60*60*1000;
}
private DateTime changeZone(int offset) {
return System.TimeZone.CurrentTimeZone.ToUniversalTime
(DateTime.Now).AddMilliseconds(offset);
}
private double getUnix(DateTime dt, int offset) {
DateTime date = System.TimeZone.CurrentTimeZone.ToUniversalTime
(dt).AddMilliseconds(offset);
TimeSpan ts = date - new DateTime(1970,1,1,0,0,0);
double unixTime = ts.TotalMilliseconds;
return unixTime;
}
private DateTime getDateFromUnix(double unix) {
DateTime date = new DateTime(1970,1,1,0,0,0).AddMilliseconds(unix);
return date;
}
The way it would work is you would set getOffset to the timezone you're working with (such as -7 would be for PST) and you would run it through the other functions to get the desired result.
The question I have is, will it work? I don't have .NET on the machine I'm using right now so I can't test that myself. Works great for EST, though.
Also, some questions about the Unix timestamp. Is it measured in milliseconds? I'm not sure if I should be returning the seconds or milliseconds with it.
Last question:
Is System.TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now) the same as DateTime.UtcNow?