Search code examples
androidkotlintimedatetime-formatmilliseconds

Kotlin - Issue in getting milliseconds for Time passed


I have created below method to get the milliseconds from 12 hour format time :

fun getMillisecondsFromTime(time: String): String {
    val formatter = SimpleDateFormat("hh aa")
    formatter.isLenient = false

    val oldDate = formatter.parse(getLocaleTime(time,"hh aa"))
    val oldMillis = oldDate.time
    return "" + oldMillis
}

I am calling this method as below for four different times:

var strTime1:String = DateUtils.getMillisecondsFromTime("1 PM")//13 * 3600
var strTime2:String = DateUtils.getMillisecondsFromTime("2 PM")//14 * 3600
var strTime3:String = DateUtils.getMillisecondsFromTime("1 AM")//1 * 3600
var strTime4:String = DateUtils.getMillisecondsFromTime("2 AM")//2 * 3600

Result am getting is wrong. i.e. for 1 PM milliseconds should be 48600 But, am getting :

1 PM >>>>>: 45000000, should be 48600

2 PM >>>>>: 48600000, should be 50400

What might be the issue?

EDIT : getting local time as below :

fun getLocaleTime(date: String, timeFormat: String): String {

    val df = SimpleDateFormat(timeFormat, Locale.ENGLISH)
    df.timeZone = TimeZone.getTimeZone("UTC")
    val date = df.parse(date)
    df.timeZone = TimeZone.getDefault()
    val formattedDate = df.format(date)
    return formattedDate
}

Solution

  • You need to get hours of the day using Calendar. And then multiply it with 3600. Like

    fun getMillisecondsFromTime(time: String): String {
        val formatter = SimpleDateFormat("hh aa")
        formatter.isLenient = false
    
        val oldDate = formatter.parse(getLocaleTime(time,"hh aa"))
        // val oldMillis = oldDate.time
    
        val cal = GregorianCalendar.getInstance()
        cal.time = oldDate
        val hourIn24Format = cal.get(Calendar.HOUR_OF_DAY)
    
        return "" + (hourIn24Format * 3600)
    }
    

    Your current code is returning time in millies from milliseconds since January 1, 1970, 00:00:00 GMT to the time you gave as input.


    Note:

    I am not sure what you are trying to achieve in this way, but this seems not a good way. If you can explain more about your requirements, I or any other can guide you for better ways.