Converting timestamp returns the wrong date – Kotlin

Issue

I have this code

val today = Calendar.getInstance().get(Calendar.DAY_OF_YEAR)
val dueDay = Calendar.getInstance()
dueDay.timeInMillis = 1708395041
val dueDate = dueDay.get(Calendar.DAY_OF_YEAR)
val dateFormat = SimpleDateFormat("hh:mm a", Locale.getDefault())
val fullDateFormat = SimpleDateFormat("MMM dd, hh:mm a", Locale.getDefault())
Log.d("t","date ${fullDateFormat.format(Date(1708395041)))

Why in logs I see Jan 20, 01:14 PM

But if i go this website https://www.unixtimestamp.com/ the actual date is Tue Feb 20 2024 02:10:41

Solution

fun timeStampToReadableDate(timestamp: Long): String {
    val date = Date(timestamp * 1000)
    val df = SimpleDateFormat("dd MMM yyyy hh:mm:ss", Locale.ENGLISH)
    df.timeZone = TimeZone.getDefault()

    return df.format(date)
}

Answered By – Saurav Suman

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *