Database DateTimeValue extensions

DatabaseColumn.DateTimeValue gives a datetime in the current timezone which may not be the same as the timezone in which the date was stored. To get the correct datetime I use this extension method.

Public Function DateTimeValue(Extends Value As DatabaseColumn, TimeZone As TimeZone) As DateTime
  Var Result As DateTime = DateTime.FromString(value.StringValue, Nil, TimeZone)
  Return Result
End Function

The usage for this is:

aDate As DateTime = aRowSet("aColumn").DateTimeValue(New TimeZone("GMT"))

To get the datetime in the current timezone I use:

Public Function DateTimeValue(Extends Value As DatabaseColumn, OriginalTimeZone As TimeZone, TargetTimeZone As TimeZone) As DateTime
  Var dt As DateTime = DateTime.FromString(Value, Nil, OriginalTimeZone)
  Return New DateTime(dt.SecondsFrom1970, TargetTimeZone)
End Function

Usage for this method is:

aDate As DateTime = aRowSet("aColumn").DateTimeValue(New TimeZone("GMT"), TimeZone.Current)

When using this method in a WebApp you can use Session.ClientTime.TimeZone as the target timezone to convert the stored date/time to the users timezone.

3 Likes