arj*_*tha 12
private fun getDateTime(s: String): String? {
try {
val sdf = SimpleDateFormat("MM/dd/yyyy")
val netDate = Date(Long.parseLong(s))
return sdf.format(netDate)
} catch (e: Exception) {
return e.toString()
}
}
Run Code Online (Sandbox Code Playgroud)
Ang*_*oko 10
这是 Kotlin 中的解决方案
fun getShortDate(ts:Long?):String{
if(ts == null) return ""
//Get instance of calendar
val calendar = Calendar.getInstance(Locale.getDefault())
//get current date from ts
calendar.timeInMillis = ts
//return formatted date
return android.text.format.DateFormat.format("E, dd MMM yyyy", calendar).toString()
}
Run Code Online (Sandbox Code Playgroud)
虽然是 Kotlin,但还是得使用 Java API。转换1510500494
您在问题评论中提到的值的 Java 8+ API 示例:
import java.time.*
val dt = Instant.ofEpochSecond(1510500494)
.atZone(ZoneId.systemDefault())
.toLocalDateTime()
Run Code Online (Sandbox Code Playgroud)
val sdf = SimpleDateFormat("dd/MM/yy hh:mm a")
val netDate = Date(item.timestamp)
val date =sdf.format(netDate)
Log.e("Tag","Formatted Date"+date)
Run Code Online (Sandbox Code Playgroud)
“sdf”是变量“SimpleDateFormat”,我们可以根据需要设置日期格式。
“netDate”是日期的变量。在 Date 中,我们可以使用 sdf.format(netDate) 发送时间戳值并通过 SimpleDateFormat 打印该日期。
class DateTest {
private val simpleDateFormat = SimpleDateFormat("dd MMMM yyyy, HH:mm:ss", Locale.ENGLISH)
@Test
fun testDate() {
val time = 1560507488
println(getDateString(time)) // 14 June 2019, 13:18:08
}
private fun getDateString(time: Long) : String = simpleDateFormat.format(time * 1000L)
private fun getDateString(time: Int) : String = simpleDateFormat.format(time * 1000L)
}
Run Code Online (Sandbox Code Playgroud)
请注意,我们乘以1000L,而不是 1000。如果您将整数 (1560507488) 乘以 1000,您将得到错误的结果:1970 年 1 月 17 日,17 : 25 : 59。
实际上就像Java。尝试这个:
val stamp = Timestamp(System.currentTimeMillis())
val date = Date(stamp.getTime())
println(date)
Run Code Online (Sandbox Code Playgroud)
小智 5
这对我有用 - 需要很长时间
import java.time.*
private fun getDateTimeFromEpocLongOfSeconds(epoc: Long): String? {
try {
val netDate = Date(epoc*1000)
return netDate.toString()
} catch (e: Exception) {
return e.toString()
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16910 次 |
最近记录: |