Search code examples
javadatekotlinepoch

Java Date to Epoch, limited by Api 21 (Android) with Java7


I've seen many useful responses on this, but using classes unavailable to me.

I have a correct Date object, and i've tryied different things, but when a review the result here I can see, it's not working.

I can only use Java7 (or kotlin equivalent)

Here is my current incorrect code:

@JvmStatic fun getEpochNumberFromDate(date: Date):String{

        var calendar : Calendar = Calendar.getInstance()
        calendar.isLenient = false
        calendar.set(date.year, date.day,date.month,date.hours,date.minutes)

        Log.d("zzz","calendar date : "+calendar.timeInMillis.toString())

        Log.d("zzz","year: "+date.year+", month:"+date.month+",  date.time.toString():"+date.time.toString())


        return date.time.toString()
    }

Solution

  • You're overcomplicating it. There is no need to use a Calendar at all. Date.getTime() returns milliseconds since epoch. You just need to divide by 1000. If you're seeing other differences from that website, it's probably because of timezone issues.