Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin convert TimeStamp to DateTime

I'm trying to find out how I can convert timestamp to datetime in Kotlin, this is very simple in Java but I cant find any equivalent of it in Kotlin.

For example: epoch timestamp (seconds since 1970-01-01) 1510500494 ==> DateTime object 2017-11-12 18:28:14.

Is there any solution for this in Kotlin or do I have to use Java syntax in Kotlin? Please give me a simple sample to show how I can resolve this problem. Thanks in advance.

this link is not an answer to my question

like image 590
DolDurma Avatar asked Nov 12 '17 15:11

DolDurma


People also ask

How to parse timestamp to date in Kotlin?

Android Dependency Injection using Dagger with Kotlin As Kotlin is interoperable with Java, we will be using Java utility class and Simple Date Format class in order to convert TimeStamp into DateTime.

What is instant Kotlin?

kotlin.Any. ↳ java.time.Instant. An instantaneous point on the time-line. This class models a single instantaneous point on the time-line.


2 Answers

private fun getDateTime(s: String): String? {     try {         val sdf = SimpleDateFormat("MM/dd/yyyy")         val netDate = Date(Long.parseLong(s) * 1000)         return sdf.format(netDate)     } catch (e: Exception) {         return e.toString()     } } 
like image 176
arjun shrestha Avatar answered Oct 02 '22 13:10

arjun shrestha


Although it's Kotlin, you still have to use the Java API. An example for Java 8+ APIs converting the value 1510500494 which you mentioned in the question comments:

import java.time.*  val dt = Instant.ofEpochSecond(1510500494)                 .atZone(ZoneId.systemDefault())                 .toLocalDateTime() 
like image 30
t0r0X Avatar answered Oct 02 '22 15:10

t0r0X