« Oracle Calendar with Palm conduit won't sync | Main

Unix Time for ASP.NET 3.5 (VB 2008)

I'm a little new to ASP.NET, so maybe I'll figure out later that I didn't need to do this...but I badly miss PHP's date functions. Working with dates in PHP is so easy that I sometimes play with it for fun.

The date object in PHP used Unix Time, which is the number of seconds since midnight GMT on 1 January 1970. Right this second, that number is 1208466537. From what I can tell, ASP.NET does not use this number — the date right now is 04/17/2008 04:09:12 PM. That's alright if you're in a locale that is compatible with that format (i.e., the US), but if you're somewhere else, you've gotta mess around. Furthermore, you have to be cognizant of the time zone. There is no time zone in Unix Time. PHP figures out the local time based on your time zone environment variable. Besides all that, Unix Time is simply an integer, which is easy to store in a database, and easy to manipulate. ASP.NET's date object is ultimately a string, which takes up more space and is harder to work with. (To be fair, ASP's date functions seem quite capable of parsing and manipulating that string.)

I can't do anything the easy way, so I whipped up some code to generate and read Unix Time in VB 2008. First, create the number from the current date and time:

	
Dim DTDate As Date = DateTime.Now
Dim Epoch As Date = "01/01/1970"
Dim TZone As TimeZone = TimeZone.CurrentTimeZone
Dim TimeZoneOffset As String = TZone.GetUtcOffset(Now).ToString().Substring(0, 3)
Dim TZORaw As Integer = Convert.ToInt32(TimeZoneOffset) * 3600

Dim TZO As Integer

if TZORaw < 0 Then
TZO = 0 - TZORaw
Else
TZO = TZORaw
End If

Dim UnixTime As Integer = DateDiff(DateInterval.Second, Epoch, DTDate) + TZO


You wind up with an Integer called UnixTime which will contain your number. I'd much rather store that number in a table. This will work for any time zone that is based on a whole-number hour. Those wacky zones over in India and elsewhere will fail. I also just realized that if your local date format is different than "MM/dd/yyyy" it won't work, so you'd need to change that string. A bit of code is needed to convert it back to a human-readable format:

Dim Today As Date = Epoch.AddSeconds(UnixTime - TZO)
Format(Today.ToSting(), "MM/dd/yyyy hh:mm:ss tt")

This will basically get it back to ASP's "natural" date format. Wonderful.

Comments

Nice to be visiting your blog again, it has been weeks for me. Well, this is the article that I’ve been waited for so long. Thanks,