Android Question Problem While converting datetime string to ticks

jcredk

Member
Licensed User
Longtime User
Hi all,

Based on another post and a good code example (http://www.b4x.com/android/forum/threads/convert-utc-to-ticks-and-vice-versa.36592/#post-215767).

I try to convert the datetime string I receive in a long (ticks).

My code is as below and it fails while trying to parse (then go in catch)

Any idea where my mistake is please ?

my Date string looks like: "Wed, 05 Feb 2014 06:55:39 GMT"
My code looks like:
B4X:
Sub TimeToUTC(lTicksIn As Long) As String
    Dim psCurrFmt As String
    Dim piCurrOff As Int
    Dim psDate As String
    psCurrFmt = DateTime.DateFormat
    piCurrOff = DateTime.TimeZoneOffset
    DateTime.DateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    DateTime.SetTimeZone(0)
    psDate = DateTime.Date(lTicksIn)
    DateTime.DateFormat = psCurrFmt
    DateTime.SetTimeZone(piCurrOff)
    Return psDate
End Sub

Sub ParseUTCstring(utc As String) As Long
   Dim df As String = DateTime.DateFormat
   Dim res As Long
   If utc.CharAt(3)="," Then
      Try
        DateTime.DateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
        res = DateTime.DateParse(utc)     'IT CRASHES HERE
        Dim reverse As String=TimeToUTC(res)
      Catch
        res = 0
        LogColor("Error parsing Date 1: " & utc, Colors.Red)
      End Try
   Else If utc.CharAt(10) = "T" Then
     'convert the second format to the first one.
     If utc.CharAt(19) = "." Then utc = utc.SubString2(0, 19) & "+0000"
     DateTime.DateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
   Else
     DateTime.DateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
   End If
   Try
     res = DateTime.DateParse(utc)
   Catch
     res = 0
    LogColor("Error parsing Date 2: " & utc, Colors.Red)
   End Try
   DateTime.DateFormat = df
   Return res
End Sub
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
As you know the format you can use a simpler code:
B4X:
Sub ParseUTCstring(utc As String) As Long
  Dim df As String = DateTime.DateFormat
  Dim res As Long
   Try
     DateTime.DateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
     res = DateTime.DateParse(utc)
   Catch
     res = 0
   Log("Error parsing Date 2: " & utc)
  End Try
  DateTime.DateFormat = df
  Return res
End Sub
 
Upvote 0

jcredk

Member
Licensed User
Longtime User
I have added the lastException.Message in the log file ...

I have following log file
B4X:
Error parsing Date 1: Wed, 05 Feb 2014 08:40:03 GMT
java.text.ParseException: Unparseable date: "Wed, 05 Feb 2014 08:40:03 GMT" (at offset 0)

After a few researches on the java part of stackoverflow, I found the "java way":
B4X:
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.ENGLISH);
As last parameter is mandatory to have a proper working on non english devices, and as mine is french ... It might be the problem :(

Any idea on how to set this parameter from B4A and reset it back to its original value after parsing ?
 
Upvote 0
Top