Web Analytics Made Easy -
StatCounter C# Timezone test - CodingForum

Announcement

Collapse
No announcement yet.

C# Timezone test

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • C# Timezone test

    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.

    Code:
    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?
    Last edited by Shinykirby; Apr 8, 2009, 05:01 PM.

  • #2
    Everything I posted seems to work, so disregard that. Timezone conversion works great.
    My last question still applies, however. I can't find the difference between the two...

    --

    Instead of triple posting, I thought I'd edit my post instead because I have another question. The form I'm working on has multiple timers, as well as Invalidate() being called several times a second due to an object I'm painting on the screen. The problem is that several of these timers and Invalidate() being called so much tends to use a lot of memory.

    How can I get CPU usage down when working with multiple timers? And for that matter, should I be using System.Windows.Forms.Timer or System.Threading.Timer?
    Last edited by Shinykirby; Apr 9, 2009, 11:25 AM.

    Comment

    Working...
    X