B4J Question DateTime conversion

atiaust

Active Member
Licensed User
Longtime User
Hi All,

I have a DateTime string "yyyy-MM-dd HH:mm:ss" which is a Mysql formatted date.
I am trying unsuccessfully to change it to "dd/MM/yyyy" and "HH:mm:ss".

All my efforts give me an error:
Error: (ParseException) java.text.ParseException: Unparseable date: "2016-12-20 07:33:45.0"

Does anyone know a conversion routine without pulling the string apart bit by bit and reassembling?

Thanks
 

derez

Expert
Licensed User
Longtime User
Try this concept:
-Define the datetime format like the string you get
-Get the ticks value of the string
-Define the required format
-Change the ticks to date and time string

But I think that by doing 3 regex.split you get all the separate values and can reconstruct the new string easily:
Split by " " to date and time
Split date by "-"
Split time by ":"
 
Upvote 0

atiaust

Active Member
Licensed User
Longtime User
Erel,

The Mysql DateTime is stored as a string "yyyy-MM-dd HH:mm:ss" ie DateTime now is "2016-12-20 18:10:00"

I want to convert date and time to "20/12/2016" & "06:10:00 PM" and also to ticks.

Thanks
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
Sub AppStart (Args() As String)
   Dim t As Long = ConvertSQLDateTime("2016-12-20 18:10:00")
   Log($"$DateTime{t}"$)
End Sub

Sub ConvertSQLDateTime(s As String) As Long
   DateTime.DateFormat = "yyyy-MM-dd HH:mm:ss"
   Dim ticks As Long = DateTime.DateParse(s)
   DateTime.DateFormat = "dd/MM/yyyy"
   DateTime.TimeFormat = "hh:mm:ss a"
   Return ticks
End Sub
 
Upvote 0

atiaust

Active Member
Licensed User
Longtime User
Thanks Erel & derez,

This works and displays the time and date as required.

B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Private Label2 As Label
    Private Label4 As Label
    Private Label6 As Label
    Private Label8 As Label
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("frmMain") 'Load the layout file.
    Dim s As String = "2016-12-20 18:10:00"    ' Mysql DateTime string - This is how Mysql stores DateTime
    Dim t As Long = ConvertSQLDateTime(s)    ' Returns No of Ticks from DateTime
   Log($"$DateTime{t}"$)
   Label2.Text = s
   Label4.Text = getDate(t)
   Label6.Text = getTime(t)
   Label8.Text = t
    MainForm.Show
End Sub

Sub ConvertSQLDateTime(s As String) As Long
   DateTime.DateFormat = "yyyy-MM-dd HH:mm:ss"
   Dim ticks As Long = DateTime.DateParse(s)
   Return ticks
End Sub

Sub getDate(date As Long) As String
    DateTime.DateFormat = "dd/MM/yyyy"
    Dim newDate As String = DateTime.Date(date)
    Return newDate    ' returns date as "20/12/2016"
End Sub

Sub getTime(time As Long) As String
    DateTime.TimeFormat = "hh:mm:ss a"
    Dim newTime As String = DateTime.Time(time)
    Return newTime    ' returns time as "06:10:00 PM"
End Sub
 
Upvote 0
Top