Profile
September 19, 2022

How To Format Date in Kotlin - All in One Solution

Are you worrying? How to format timestamp to String date? here you can find the complete solution in one place.

How To Format Date in Kotlin - All in One Solution

Here we have created a generic Method that you can use where ever you require. 

public fun getDateFormattedFromTimeStamp(timestamp: Long, format: String): String {
   val calender = Calendar.getInstance()
   calender.timeInMillis = timestamp
   val dateFormatter = SimpleDateFormat(format, Locale("en"))
   return dateFormatter.format(calender.time)
}

 

 

Usage: Time Stamp To Simple String Date Format

 

getDateFormattedFromTimeStamp(Calendar.getInstance().timeInMillis, "yyyy, MMM dd")
output:
// 2022, Sep 03

 

An explanation for other Date Formats
 

Year:

yyyy”  4-digit Year (eg. 2022)
yy”  2-digit Year (eg. 22)

 

Month:

MM2-digit Month (eg. 01)
MMM3- character Month (eg. Jan)
MMMMFull characters Month (eg. January)

 

Day:

dd” or “dDay in a month (eg. 19)

DD” or “DDay in Year (eg. 262)

 

Other Examples:

val timestamp = 1663584353488
DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy-MMM-dd") // 2022-Sep-19
DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy, MMM dd") // 2022, Sep 19
DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy/MMM/dd") // 2022/Sep/19
DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy/MM/dd") // 2022/09/19
DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMM, yy") // 19 Sep, 22
DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd, MMM yy") // 19, Sep 22
DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd, MMM yyyy") // 19, Sep 2022
DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMM, yyyy") // 19 Sep, 2022
DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MM, yyyy") // 19 09, 2022
DateUtil.getDateFormattedFromTimeStamp(timestamp, "DD MM, yyyy") // 262 09, 2022
DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMMM, yyyy") // 19 September, 2022


 

 

Last edited on September 19, 2022 by Admin

Latest articles