Android Question problem with TimeZone/Daylight

marcick

Well-Known Member
Licensed User
Longtime User
I have a date as string coming from a GPS system that need to be represented with the timezone and daylight saving settings.

This is the code that works fine

B4X:
    Dim dt As Long=DateTime.Dateparse("2018-03-25 02:01:22")
    dt=dt+(DateTime.GetTimeZoneOffsetAt(dt)*3600000)
    Log(DateTime.Date(dt))

The problem in the example above is that the original date "2018-03-25 02:01:22" does not exist in Italy (on 25 March the hour jumps from 02:00 to 03:00) and that code crash with "unparseable date"
Where I'm wrong ?
 

udg

Expert
Licensed User
Longtime User
Hi @marcick ,
look at DateTime.DateFormat for your "date unparseable" error. Probaby a date in the form (dd/MM/yyyy) will be accepted on your device.
A good practice is to :
- store current format setting
- modify setting to cope with data to be worked on
- work on data (e.g. date parsing)
- restore original format

More, you need to use DateTimeParse if you need to parse a date and a time in a single value.
BTW, the proper way to add time is DateUtils.AddPeriod
 
Last edited:
Upvote 0

marcick

Well-Known Member
Licensed User
Longtime User
Hi udg,
Data from the GPS system arrive in that format so I change my Datetime.DateFormat according to it.
All data are processed correctly without problem, the crash happens only between 02:00 and 03:00 AM of the last sunday of March.
I can use DateUtils, ok, but before I need to convert the string date to tick and that is the point where the error happen.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Whenever you call GetTimeZoneOffsetAt you should know that you are doing something wrong.

The problem here is that the string time zone is different than the device time zone. The solution is to add it to the string:
B4X:
DateTime.DateFormat = "yyyy-MM-dd HH:mm:ss z"
Dim t As Long = DateTime.Dateparse("2018-03-25 02:01:22" & " GMT")
Log($"$DateTime{t}"$)
 
  • Like
Reactions: udg
Upvote 0

marcick

Well-Known Member
Licensed User
Longtime User
Yes, I realize now that could be dangerous using my code.
Your code is ok and simpler.
Is there a smart way to detect if a given date has the daylight correction ?
I see in the log I can have "CET" or "CEST", but in other timezone will be different so it's not correct to look at the final characters "CEST"
 
Upvote 0

marcick

Well-Known Member
Licensed User
Longtime User
Yes, your code works, but I want to represent if a certain datetime has or not the daylight correction, without showing CET or CEST.
Well, I know how to do the calculation, but because Android already do it I was asking if there is a quick way to retrieve this info.
 
Upvote 0
Top