Android Question Parsing date and time under different locales

trueboss323

Active Member
Licensed User
Hello, I'm trying to parse both a date and time. I have a user select both date and time from a dialog. It returns the value as String such as "Wed Jan 24 19:32:16 MST 2018" , and I'm trying to get it in ticks:
B4X:
DateTime.DateFormat = "EEE MMM dd hh:mm:ss Z yyyy"
            If hour >12 Then DateTime.DateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
            Dim lngdate As Long = DateTime.DateParse(full_date)
            log(lngdate)
The full_date is what is returned as string. The hour returns the hour selected from the dialog. If the user has clock in 24 hour format, it fails so I have it change the date format.
If it try to run it with a non-English locale then it fails. So I have this in Service Create sub in the Starter module.
B4X:
    Dim jo As JavaObject
jo.InitializeStatic("java.util.Locale").RunMethod("setDefault", Array(jo.GetField("US")))


The code works, but then other areas of my app that show the date/time also get shown in English locale. How can I leave those unchanged?
 

udg

Expert
Licensed User
If I understand it correctly, you could simply save your current locale, modify it when receiving data from the input control, parse the result then revert back to saved locale.
 
Upvote 0

trueboss323

Active Member
Licensed User
Upvote 0

udg

Expert
Licensed User
Could you give an example how I could do that ?
Here you can read about getDefault , a static method returning current Locale, not so different from setDafult
Or follow Erel's advice and use DateDialog.

public static Locale getDefault()
Gets the current value of the default locale for this instance of the Java Virtual Machine.
The Java Virtual Machine sets the default locale during startup based on the host environment. It is used by many locale-sensitive methods if no locale is explicitly specified. It can be changed using the setDefault method.

Returns:
the default locale for this instance of the Java Virtual Machine
 
Upvote 0

trueboss323

Active Member
Licensed User
Here you can read about getDefault , a static method returning current Locale, not so different from setDafult
Or follow Erel's advice and use DateDialog.

Here's a simple example I try to do:
B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("1")
  
    DateTime.DateFormat = DateTime.DeviceDefaultDateFormat
    DateTime.TimeFormat = DateTime.DeviceDefaultTimeFormat
  
    Label1.Text = DateTime.Date(DateTime.Now) & " " &DateTime.Time(DateTime.Now)

End Sub

When the app loads I expect the format to be in the device's language. When i have the language set to English(US) I should get it as: "Jan 25, 2018 11:49:52 AM"
Now I tried setting the languages to Italian,German, and Polish. I get the same format. If I remove the line from the starter code then it works properly.
 
Upvote 0
Top