B4A Class Save the Date! with SimpleDateFormatter

stanmiller

Active Member
Licensed User
B4A/B4J Class - Save the Date! with SimpleDateFormatter

SimpleDateFormatter is a helper class that uniquely formats the current date and time independent of the application-wide B4X DateTime.Format. This allows developers to format dates without needing to save and restore the calling application's format preference.

See SimpleDateFormat for format specificatons:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Example:
B4X:
Private sdf1 As SimpleDateFormatter
Private sdf2 As SimpleDateFormatter

' Specify different formats
sdf1.Initialize("yyMMdd-HHmmss")
sdf2.Initialize("EEE, MMM d, ''yy")

Log( "SimpleDateFormatter Demo" )
Log( "------------------------" )

Log( "B4X DateTime:  " & DateTime.Date(DateTime.Now) & " " & DateTime.Time(DateTime.now) )
Log( "SimpleDateFormatter1:  " & sdf1.GetDateTime() )
Log( "SimpleDateFormatter2:  " & sdf2.GetDateTime() )

' SimpleDateFormatter Demo
' ------------------------
' B4X DateTime:  12/10/2016 14:00:07
' SimpleDateFormatter1:  161210-140007
' SimpleDateFormatter2:  Sat, Dec 10, '16
SimpleDateFormatter Class
B4X:
'**********************************************************************************
'*
'* SimpleDateFormatter.bas - Formats current date and time to string without
'*                           changing the application's global DateTime.Format
'*
'* Copyright (C) 2016 MacThomas Engineering (www.macthomasengineering.com)
'*
'**********************************************************************************

#Region Revision History
'**********************************************************************************
'* Revision History:
'*
'* No.        Who  Date        Description
'* ======     ===  ==========  ====================================================
'* 1.00.1     MTE  2016/12/11  - Revised init to inline Java class to show
'*                               component names using constants
'*                             - Fixed typos and updated formatting
'* 1.00.0     MTE  2016/12/10  - First release
'*
'**********************************************************************************
#End Region

'Class module
Sub Class_Globals

    Private joSimpleDateFormatter As JavaObject
    Private oSimpleDateFormat As Object = Null

End Sub

'----------------------------------------------------------------------------------
' Initialize() - SimpleDateFormatter
'
' Example:  Dim sdf as SimpleDateFormatter
'           sdf.Initialize( "yyMMdd-HHmmss" )
'           Log( sdf.GetDateTime() )
'
' See SimpleDateFormat for format specificatons
' http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
'
' If the date format is invalid GetDateTime() will return an empty string
'
Public Sub Initialize( sDateFormat As String )
    Private jo As JavaObject
    Private Const B4X_CLASS_NAME="simpledateformatter" As String                'Name of this .BAS file without ext in lowercase
    Private Const INLINE_JAVA_CLASS_NAME="SimpleDateFormatterInline" As String  'Name of inline Java class as defined
    
    ' Get the package name
    jo.InitializeStatic("anywheresoftware.b4a.BA")
    Private sPackageName As String = jo.GetField("packageName")
  
    ' Set reference to the inline Java class
    ' (e.g. com.macthomasengineering.simpledatedemo.simpledateformatter.SimpleDateFormatterInline )
    joSimpleDateFormatter.InitializeStatic( sPackageName   & "." & _
                                            B4X_CLASS_NAME & "." & _
                                            INLINE_JAVA_CLASS_NAME )

    'Get instance of SimpleDateFormat object with requested format
    oSimpleDateFormat = joSimpleDateFormatter.RunMethod( "getSimpleDateFormat", Array( sDateFormat ) )

    ' Report invalid format
    If ( oSimpleDateFormat = Null ) Then
        Log("SimpleDateFormatter: Invalid date format=" & sDateFormat )
    End If

End Sub

'----------------------------------------------------------------------------------
' GetDateTime() - Returns formatted date and time string
' based on format specified at initialization.
'
' Example:  Dim sdf as SimpleDateFormatter
'           sdf.Initialize( "yyMMdd-HHmmss" )
'           Log( sdf.GetDateTime() )
'
Public Sub GetDateTime() As String
    Private sDateString As String

    If ( oSimpleDateFormat = Null ) Then
        Log( "SimpleDateFormatter: Not initialized.")
       Return ("")
    End If

    ' Get current date and time in format specified
    sDateString = joSimpleDateFormatter.RunMethod( "getDateTime", Array( oSimpleDateFormat ) )

    Return ( sDateString )        
End Sub

#if java

import java.util.Date;
import java.text.SimpleDateFormat;

public static class SimpleDateFormatterInline {

    /**------------------------------------------------------ getSimpleDateFormat()
    * Gets instance of SimpleDataFormat object
    * Parameter: Date format spec (ex. "yyMMdd-HHmmss" )
    * Returns: Reference to SimpleDateFormat object
    */
    public static SimpleDateFormat getSimpleDateFormat( String dateFormat ) {
        SimpleDateFormat sdf;
    
        try {
            sdf = new SimpleDateFormat( dateFormat );
        }
        catch ( IllegalArgumentException ex ){
            sdf = null;
        }
        
        return (sdf);
    }    

    /**-------------------------------------------------------------- getDateTime()
    * Get formatted date and time string
    * Parameter: SimpleDateFormat object reference
    * Returns: Current date and time formatted as String
    */
    public static String getDateTime( SimpleDateFormat sdf ) {
        String dateString;

        // If null return empty string
        if ( sdf == null ) return ("");
    
        // Format current date and time
        dateString = sdf.format( new Date() );

        return (dateString);        
    }
}

#end if
Demo project attached.
 

Attachments

Last edited:
Top