Common functions in Kotlin

Functions:

  • Set Icons Color Function
  • Check expiration date
  • Format Time (Int to String)
  • Format Time (LocalTime to String)
  • Format Time (Calendar to String)
  • Format Date (Int to String)
  • Format Duration Time
  • Difference Date
  • Format Money (Double to String)
  • BitMap To String
  • String To BitMap
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64.*
import android.widget.ImageView
import java.io.ByteArrayOutputStream
import java.math.BigDecimal
import java.text.NumberFormat
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.*


/**
 * object containing common functions
 * for the App
 */
object CommonApp{

    //Set Icons Color Function
    fun setIconColor(context: Context, icon: ImageView?, color: Int){

        icon?.setColorFilter(
            ContextCompat.getColor(context, color)
        )
    }

    //Check expiration date
    fun isDateExpired(dayOfMonth: Int, monthOfYear: Int, year: Int): Boolean {

        val expDate = GregorianCalendar(year, monthOfYear, dayOfMonth)
        val now = GregorianCalendar()

        return now.after(expDate)
    }

 //////////////////////// FORMAT TIME /////////////////////////////
    fun formatTime(time: Int): String {

        return SimpleDateFormat("HH:mm")
            .format(Date(time * 1000L))
    }

    fun formatTime(time: LocalTime): String {

        val formatter = DateTimeFormatter.ofPattern("HH:mm")
        return time.format(formatter)
    }

    fun formatTime(time: Calendar): String {

        val format = SimpleDateFormat("HH:mm")
        return format.format(time.time)
    }

//////////////////////// FORMAT DATE /////////////////////////////
    fun formatDate(date: Int): String {

        return SimpleDateFormat("dd MMMM yyyy")
            .format(Date(date * 1000L))
    }

    fun formatMonthYear(date: Int): String {

        return SimpleDateFormat("MMMM yyyy")
            .format(Date(date * 1000L))
    }



 //////////////////////// FORMAT MINUTES /////////////////////////////
    fun formatDurationTime(minutes: Int, initial: String): String = if (minutes < 60) {

        "$minutes $initial"

    } else {

        val min = (minutes) % 60
        val hours = (minutes) / 60
        String.format("%02dh %02dm", hours, min)
    }

    fun differenceDate(fromDateTime: LocalDateTime, toDateTime: LocalDateTime) {

        var tempDateTime = LocalDateTime.from(fromDateTime)
        
        val days = tempDateTime.until(toDateTime, ChronoUnit.DAYS)
        tempDateTime = tempDateTime.plusDays(days)


        val hours = tempDateTime.until(toDateTime, ChronoUnit.HOURS)
        tempDateTime = tempDateTime.plusHours(hours)

        val minutes = tempDateTime.until(toDateTime, ChronoUnit.MINUTES)
        tempDateTime = tempDateTime.plusMinutes(minutes)

        val seconds = tempDateTime.until(toDateTime, ChronoUnit.SECONDS)

    }

 //////////////////////// FORMAT MONEY /////////////////////////////
    fun formatMoney(amount: Double): String {
        val formatter = NumberFormat.getCurrencyInstance(Locale.ITALY)
        return formatter.format(BigDecimal(amount))
    }

    
 //////////////////////// CONVERT BITMAP /////////////////////////////
    fun BitMapToString(bitmap: Bitmap): String {
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos)
        val b = baos.toByteArray()
        return encodeToString(b, DEFAULT)
    }

    fun StringToBitMap(encodedString: String?): Bitmap? {
        return try {
            val encodeByte: ByteArray = decode(encodedString, DEFAULT)
            BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.size)
        } catch (e: Exception) {
            e.message
            null
        }
    }
}

Calcolo lettera di controllo codice fiscale – Kotlin

Il sedicesimo carattere del Codice Fiscale Italiano, ha la funzione di controllo dell’esatta trascrizione dei primi quindici caratteri.

Esso viene determinato nel modo seguente:

  1. Convertire in numeri tutti i caratteri che compongono il codice fiscale in posizione pari, rispettando i corrispondenti della tabella A;
  2. Convertire in numeri tutti i caratteri che compongono il codice fiscale in posizione dispari, rispettando i corrispondenti della tabella B;
  3. Addizionare tutti i numeri ottenuti dalla tabella A e B;
  4. Calcolare il resto della divisione tra la somma dei numeri e 26 (sommaNumeri % 26)
  5. Determinare la lettera alfabetica corrispondente al resto dell’operazione dalla tabella C.

Tabella A Per la conversione dei sette caratteri con posizione di ordine pari:

A o zero  = zero           O   = 14
B o 1     = 1              P   = 15
C o 2     = 2              Q   = 16
D o 3     = 3              R   = 17
E o 4     = 4              S   = 18
F o 5     = 5              T   = 19
G o 6     = 6              U   = 20
H o 7     = 7              V   = 21
I o 8     = 8              W   = 22
J o 9     = 9              X   = 23
K         = 10             Y   = 24
L         = 11             Z   = 25
M         = 12             -      -
N         = 13             -      -

Tabella B Per la conversione degli otto caratteri con posizione di ordine dispari:

A o zero  = 1              O   = 11
B o 1     = 0              P   = 3 
C o 2     = 5              Q   = 6 
D o 3     = 7              R   = 8 
E o 4     = 9              S   = 12
F o 5     = 13             T   = 14
G o 6     = 15             U   = 16
H o 7     = 17             V   = 10
I o 8     = 19             W   = 22
J o 9     = 21             X   = 25
K         = 2              Y   = 24
L         = 4              Z   = 23
M         = 18             -      -
N         = 20             -      -

Tabella C I valori numerici determinati vengono addizionati e la somma si divide per il numero 26. Il carattere di controllo si ottiene convertendo il resto di tale divisione nel carattere alfabetico ad esso corrispondente nella tabella:

zero = A             14 = O
   1 = B             15 = P
   2 = C             16 = Q
   3 = D             17 = R
   4 = E             18 = S
   5 = F             19 = T
   6 = G             20 = U
   7 = H             21 = V
   8 = I             22 = W
   9 = J             23 = X
  10 = K             24 = Y
  11 = L             25 = Z
  12 = M             -    -
  13 = N             -    -

Algoritmo in Kotlin

//Corrispettivi caratteri codice fiscale in posizione pari
private val charInEvenPosition = mapOf(
    "0" to 0, "1" to 1, "2" to 2,
    "3" to 3, "4" to 4, "5" to 5,
    "6" to 6, "7" to 7, "8" to 8,
    "9" to 9, "A" to 0, "B" to 1,
    "C" to 2, "D" to 3, "E" to 4,
    "F" to 5, "G" to 6, "H" to 7,
    "I" to 8, "J" to 9, "K" to 10,
    "L" to 11, "M" to 12, "N" to 13,
    "O" to 14, "P" to 15, "Q" to 16,
    "R" to 17, "S" to 18, "T" to 19,
    "U" to 20, "V" to 21, "W" to 22,
    "X" to 23, "Y" to 24, "Z" to 25
)
//Corrispettivi caratteri codice fiscale in posizione dispari
val charInOddPosition = mapOf(
    "0" to 1, "1" to 0, "2" to 5,
    "3" to 7, "4" to 9, "5" to 13,
    "6" to 15, "7" to 17, "8" to 19,
    "9" to 21, "A" to 1, "B" to 0,
    "C" to 5, "D" to 7, "E" to 9,
    "F" to 13, "G" to 15, "H" to 17,
    "I" to 19, "J" to 21, "K" to 2,
    "L" to 4, "M" to 18, "N" to 20,
    "O" to 11, "P" to 3, "Q" to 6,
    "R" to 8, "S" to 12, "T" to 14,
    "U" to 16, "V" to 10, "W" to 22,
    "X" to 25, "Y" to 24, "Z" to 23
)
//Corrispettivi risultato del resto della divisione
private val controlChar = mapOf(
    0 to "A", 1 to "B", 2 to "C",
    3 to "D", 4 to "E", 5 to "F",
    6 to "G", 7 to "H", 8 to "I",
    9 to "J", 10 to "K", 11 to "L",
    12 to "M", 13 to "N", 14 to "O",
    15 to "P", 16 to "Q", 17 to "R",
    18 to "S", 19 to "T", 20 to "U",
    21 to "V", 22 to "W", 23 to "X",
    24 to "Y", 25 to "Z"
    )
private fun checkControlLetterFiscalCode(fiscalCode: String): Boolean {

        var numberCharInEvenPosition = 0
        var numberCharInOddPosition = 0
        val fiscalCodeWithOutControlLetter = fiscalCode.substring(0, (fiscalCode.length - 1));

        for (i in fiscalCodeWithOutControlLetter.indices) {
            //Calcolo il modulo della i-esima posizione 
            //Il calcolo prevede che la prima posizione sia identificata con 1 e non con 0
            val isEven = (i+1) % 2
            //Conversione carattere in stringa e in lettera maiuscola
            val char = fiscalCode[i].toUpperCase().toString()
            //determino se la posizione è pari o dispari e ottengo il corrispettivo dalle tabelle
            when(isEven){

                0 ->   numberCharInEvenPosition += charInEvenPosition[char] ?: error("error")
                else ->  numberCharInOddPosition += charInOddPosition[char] ?: error("error")
            }
        }
        //Calcolo del numero di controllo attraverso la formula data
        val controlNumber = (numberCharInEvenPosition + numberCharInOddPosition) % 26
        //Ottengo la corrispettiva lettera associata al numero ottenuto dal resto della divisione
        val controlChar = controlChar[controlNumber]
        //Determino la lettera di controllo presente nel codice fiscale inserito
        val currentControlChar = fiscalCode[fiscalCode.length-1].toUpperCase().toString()
        //Controllo l'uguaglianza tra la lettera di controllo inserita nel codice fiscale e quella calcolata con l'algoritmo
        return controlChar == currentControlChar
    }

Calculate gender and date of birth from the Italian tax code Android Kotlin

    private fun inverseFiscalCodeCalculate(fiscalCode: String) {

        // Letter corresponding to the month number
        val monthArray = mapOf(
            "A" to "01",
            "B" to "02",
            "C" to "03",
            "D" to "04",
            "E" to "05",
            "H" to "06",
            "L" to "07",
            "M" to "08",
            "P" to "09",
            "R" to "10",
            "S" to "11",
            "T" to "12"
        )

        // Get gender and born date
        val getNumberGender = fiscalCode.substring(9, 11).toInt()
        val getNumberDayDate = if(getNumberGender > 40) abs(getNumberGender - 40) else getNumberGender
        val getNumberMonthDate = fiscalCode.substring(8, 9)
        val getNumberYearDate = fiscalCode.substring(6, 8)
        val filterMonth = monthArray[getNumberMonthDate.toUpperCase()]

        //Check born year
        val yearCheck = parseInt(getNumberYearDate) + 1900
        val dateCheck = Calendar.getInstance()

// Check if the user is older than 85 years. This allows you to determine the millennium to read (1900 or 2000)
        dateCheck.add(Calendar.YEAR, -85) 
        val yearBorn = if (yearCheck < dateCheck.get(Calendar.YEAR))
            parseInt(getNumberYearDate)  + 2000
        else yearCheck

        //User data
        val genderString = if(getNumberGender < 32) "M" else "F"
        va bornDateString = "$getNumberDayDate/$filterMonth/$yearBorn/"

    }

Open an external App from your App Kotlin

Launch external App

Open Google Play Store if the external app is not installed on your device otherwise open the app

private fun launchApp(appPackageName: String) {

        if (appInstalledOrNot(appPackageName)) { 
            val intent: Intent = context?.packageManager?.
                getLaunchIntentForPackage(appPackageName)!!
            startActivity(intent)
        } else {

            try {
                startActivity(
                    Intent(
                        Intent.ACTION_VIEW,
                        Uri.parse("market://details?id=$appPackageName")
                    )
                )
            } catch (exception: ActivityNotFoundException) {
                startActivity(
                    Intent(
                        Intent.ACTION_VIEW,
                        Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")
                    )
                )
            }
        }

    }

Format date from integer, LocalDate or Calendar to string Kotlin

Format date from integer type

 fun formatDate(date: Int): String {

        return SimpleDateFormat("dd MMMM yyyy")
            .format(Date(date * 1000L))
    }

    fun formatMonthYear(date: Int): String {

        return SimpleDateFormat("MMMM yyyy")
            .format(Date(date * 1000L))
    }
 fun formatDate(date: LocalDate): String {

        val formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy")

        return date.format(formatter)
    }
fun formatDate(date: Calendar): String {
        val formatter = SimpleDateFormat("dd MMMM yyyy")
        return formatter.format(date.time)
    }