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?
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 ":"
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
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