Android Question Utc to central time

OliverA

Expert
Licensed User
Longtime User
How do I convert datetime from utc to central time?
Please note, internally, all time is kept UTC. "Converting" to another time only makes sense for display purposes only. So use this code snipped only if you are trying to display CST time as text, not convert the long value of the UTC time to a long value representing CST time (since that makes no sense).

B4X:
'Pre-requisite: a long variable named UTCTime that contains the time in ticks needing conversion
Dim oldOffset As Double = DateTime.TimeZoneOffset
Dim jo As JavaObject
jo.InitializeStatic("java.util.TimeZone")
Dim jo2 As JavaObject = jo.RunMethodJO("getTimeZone", Array As Object ("CST"))
'Getting the offset in milliseconds and converting it to hours for DateTime's SetTimeZone method
Dim newOffset as Double = jo2.RunMethod("getOffset", Array As Object (UTCTime)) / (1000*60*60)
DateTime.SetTimeZone(newOffset)
Log(DateTime.Time(UTCTime))
DateTime.SetTimeZone(oldOffset)

Note: If you actually know the offset amount, you can skip the whole JavaObject rigamarole and just set it directly via SetTimeZone method (just make sure to reset it when you are done). I just can't ever remember, so I rather use the textual representation and have the computer figure out the right number for me.
 
Upvote 0
Top