How to get current local date and time in Kotlin - android

How to get current Date (day month and year) and time (hour, minutes and seconds) all in local time in Kotlin?
I tried through LocalDateTime.now() but it is giving me an error saying Call requires API Level 26 (curr min is 21).
How could I get time and date in Kotlin?

Try this :
val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
val currentDate = sdf.format(Date())
System.out.println(" C DATE is "+currentDate)

My utils method for get current date time using Calendar when our minSdkVersion < 26.
fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
val formatter = SimpleDateFormat(format, locale)
return formatter.format(this)
}
fun getCurrentDateTime(): Date {
return Calendar.getInstance().time
}
Using
import ...getCurrentDateTime
import ...toString
...
...
val date = getCurrentDateTime()
val dateInString = date.toString("yyyy/MM/dd HH:mm:ss")

java.util.Calendar.getInstance() represents the current time using the current locale and timezone.
You could also choose to import and use Joda-Time or one of the forks for Android.

You can get current year, month, day etc from a calendar instance
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)
If you need it as a LocalDateTime, simply create it by using the parameters you got above
val myLdt = LocalDateTime.of(year, month, day, ... )

Try this:
val date = Calendar.getInstance().time
val formatter = SimpleDateFormat.getDateTimeInstance() //or use getDateInstance()
val formatedDate = formatter.format(date)
You can use your own pattern as well, e.g.
val sdf = SimpleDateFormat("yyyy.MM.dd")
// 2020.02.02
To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates.
The first three options require API level 29.

To get the current Date in Kotlin do this:
val dateNow = Calendar.getInstance().time

fun main(){
println(LocalDateTime.now().toString()) //2021-10-25T12:03:04.524
println(Calendar.getInstance().time) //Mon Oct 25 12:02:23 GST 2021
}
There are the above options, with the output added as comment.

You can use this function
fun getCurrentDate():String{
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
return sdf.format(Date())
}

fun now(): String {
return SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
}
val currentYear = SimpleDateFormat("yyyy",Locale.getDefault()).format(Date())
val currentMonth = SimpleDateFormat("MM",Locale.getDefault()).format(Date())
val currentDay = SimpleDateFormat("dd",Locale.getDefault()).format(Date())

checkout these easy to use Kotlin extensions for date format
fun String.getStringDate(initialFormat: String, requiredFormat: String, locale: Locale = Locale.getDefault()): String {
return this.toDate(initialFormat, locale).toString(requiredFormat, locale)
}
fun String.toDate(format: String, locale: Locale = Locale.getDefault()): Date = SimpleDateFormat(format, locale).parse(this)
fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
val formatter = SimpleDateFormat(format, locale)
return formatter.format(this)
}

Assuming that we got time in seconds we can do something like: (koltin language)
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val hour = calendarInstance.get(Calendar.HOUR)
val minute = calendarInstance.get(Calendar.MINUTE)
val ampm = if(calendarInstance.get(Calendar.AM_PM)==0) "AM " else "PM "
val date = calendarInstance.get(Calendar.DATE)
val month = calendarInstance.get(Calendar.MONTH)
val year = calendarInstance.get(Calendar.YEAR)

I use this to fetch data from API every 20 seconds
private fun isFetchNeeded(savedAt: Long): Boolean {
return savedAt + 20000 < System.currentTimeMillis()
}

Another solution is changing the api level of your project in build.gradle and this will work.

Related

How to format Firestore server timestamp in kotlin?

After I retrieve the date of data field from Firestore's Timestamp. I want to format my Timestamp date to "dd MMM yyyy, HH:mm" in my recyclerview. I tried to use DateTimeFormatter but it doesn't works.
override fun onBindViewHolder(holder: OrderListViewHolder, position: Int) {
val item = orderList[position]
orderViewModel.setOrderProduct(item.foodItem)
orderViewModel.setStatus(item.status)
val foodItem = item.foodItem?.map { it.itemName }
val date = Date(item.date!!.toDate().time)
val newDate = date.toString().substring(0, 16) + date.toString().substring(29, 34)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = newDate.format(formatter)
Log.d("dates", "${formattedDate}")
holder.orderDate.text = formattedDate
holder.foodName.text = foodItem.toString().removeSurrounding("[", "]")
holder.status.text = orderViewModel.status.value.toString()
}
Currently, I only know how to use substring to design my date format. But it's not my expected.
How can I set my Timestamp format?
fun getDateString(seconds: Long, outputPattern: String): String {
try {
val dateFormat = SimpleDateFormat(outputPattern, Locale.ENGLISH)
val calendar = Calendar.getInstance()
calendar.timeInMillis = seconds * 1000
val date = calendar.time
return dateFormat.format(date)
} catch (e: Exception) {
Log.e("utils", "Date format", e)
return ""
}
}
With this code:
val date = Date(item.date!!.toDate().time)
val newDate = date.toString().substring(0, 16) + date.toString().substring(29, 34)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = newDate.format(formatter)
you are taking a date from an item, creating a Date object, then you're adding some string manipulation. Note that toString() on a date could generate different results, based on the system preferences. This is already something you should avoid.
Then you're creating a DateTimeFormatter and using it on the newDate, that is a String, so it will not do what you are expecting.
You can obtain what you want simply by using the format on the date and not on the string:
val date = Date(item.date!!.toDate().time)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = date.format(formatter)

How to convert "yyyy-MM-dd'T'HH:mm:ssZZZZZ" to "yyyy-MM-dd" without add one day in Android?

I am develop in Android
The day of String is 2020-04-23T23:59:59-04:00
And try to use the following function to convert the time to 2020-04-23
fun changeDateFormat(strDate:String):String {
return SimpleDateFormat("yyyy-MM-dd").format(SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ").parse(strDate))
}
But it show 2020-04-24
Did I missing something ? Thanks in advance.
here is how you can achieve it
val dateInString = "2020-04-23T23:59:59-0400"
val ldt: LocalDateTime = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"))
val currentZoneId: ZoneId = ZoneId.systemDefault()
val currentZonedDateTime: ZonedDateTime = ldt.atZone(currentZoneId)
val format: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val formattedDate = format.format(currentZonedDateTime)
println(formattedDate)
You should use DateTimeFormatter and LocalDate from java.time.
for example
val timestampAsDateString = "2020-04-23T23:59:59-04:00"
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZZZZZ")
val date = LocalDate.parse(timestampAsDateString, format)
Log.d("parseTesting","Date : ${date}") // logs 2020-04-23
since LocalDate is a date without time-zone in the ISO-8601 calendar system the output is already in yyyy-MM-dd format.
Your time must not contain colon in between(-04:00)
This worked out well for me and returned the desired result
fun changeDateFormat(strDate:String):String {
val sourceSdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault())
val requiredSdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
return requiredSdf.format(sourceSdf.parse(strDate))
}

How to format in Kotlin date in string or timestamp to my preferred format?

I'm getting date data from weather API in two versions. The first one is just string like this: 2019-08-07 09:00:00 and like this: 1565209665. How do I change it to just the name of the day or day and month?
For example Monday, August.
I tried something like this in few configurations but it works only in full version. If I cat something then it throws an error:
var date = list.get(position).dt_txt
val formatter = DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss").toFormatter()
formatter.parse(date)
First API format:
val firstApiFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val date = LocalDate.parse("2019-08-07 09:00:00" , firstApiFormat)
Log.d("parseTesting", date.dayOfWeek.toString()) // prints Wednesday
Log.d("parseTesting", date.month.toString()) // prints August
Second API format:
val secondApiFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val timestamp = 1565209665.toLong() // timestamp in Long
val timestampAsDateString = java.time.format.DateTimeFormatter.ISO_INSTANT
.format(java.time.Instant.ofEpochSecond(timestamp))
Log.d("parseTesting", timestampAsDateString) // prints 2019-08-07T20:27:45Z
val date = LocalDate.parse(timestampAsDateString, secondApiFormat)
Log.d("parseTesting", date.dayOfWeek.toString()) // prints Wednesday
Log.d("parseTesting", date.month.toString()) // prints August
This is really simple
val dateFormated = SimpleDateFormat("dd/MM/yyyy").format(trans.created_date.toDate())
I hope this works for everybody, thanks to https://www.datetimeformatter.com/how-to-format-date-time-in-kotlin/
Try this code to get dayOfWeek and month name
Code
To String Date
Method
fun getAbbreviatedFromDateTime(dateTime: String, dateFormat: String, field: String): String? {
val input = SimpleDateFormat(dateFormat)
val output = SimpleDateFormat(field)
try {
val getAbbreviate = input.parse(dateTime) // parse input
return output.format(getAbbreviate) // format output
} catch (e: ParseException) {
e.printStackTrace()
}
return null
}
*How to use
val monthName=getAbbreviatedFromDateTime("2019-08-07 09:00:00","yyyy-MM-dd HH:mm:ss","MMMM")
println("monthName--"+monthName)
val dayOfWeek=getAbbreviatedFromDateTime("2019-08-07 09:00:00","yyyy-MM-dd HH:mm:ss","EEEE")
println("dayOfWeek--"+dayOfWeek)
To Timemillis
Methods
fun convertStringToCalendar( timeMillis: Long) {
//get calendar instance
val calendarDate = Calendar.getInstance()
calendarDate.timeInMillis = timeMillis
val month=getAbbreviatedFromDateTime(calendarDate,"MMMM");
val day=getAbbreviatedFromDateTime(calendarDate,"EEEE");
Log.d("parseTesting", month)// prints August
Log.d("parseTesting",day)// prints Wednesday
}
fun getAbbreviatedFromDateTime(dateTime: Calendar, field: String): String? {
val output = SimpleDateFormat(field)
try {
return output.format(dateTime.time) // format output
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
Use
val timestamp = "1565209665".toLong()
convertStringToCalendar(timestamp)
Try this
val stringDate="2019-08-07 09:00:00"
val dateFormat_yyyyMMddHHmmss = SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.ENGLISH
)
val date = dateFormat_yyyyMMddHHmmss.parse(stringDate)
val calendar = Calendar.getInstance()
calendar.setTime(date)
val dayOfWeekString = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH)
Output:
dayOfWeekString : wednesday
val timeInMillis = 1565242471228
val calendar = Calendar.getInstance()
calendar.setTimeInMillis(timeInMillis)
val dayOfWeekString = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH)
val parsedDate: String? = if(monthOfYear < 10 && dayOfMonth > 10){
"${dayOfMonth}/0${monthOfYear + 1}/${year}"
} else if(dayOfMonth < 10 && monthOfYear > 10) {
"0${dayOfMonth}/${monthOfYear + 1}/${year}"
} else if(dayOfMonth < 10 && monthOfYear < 10){
"0${dayOfMonth}/0${monthOfYear + 1}/${year}"
}else{
"0${dayOfMonth}/${monthOfYear + 1}/${year}"
}
date?.text = parsedDate
I tried different things but in Date picker this works for me in kotlin

How can I convert a Long value to date time and convert current time to Long kotlin?

The Code A can convert a long value to date value, just like 2018.01.10
I hope to get Date + Time value , such as 2018.01.10 23:11, how can I do with Kotlin?
I hope to convert current time to a long value , how can I do with Kotlin?
Thanks!
Code A
fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
return df.format(this)
}
Try this, I use SimpleDataFormat.
fun convertLongToTime(time: Long): String {
val date = Date(time)
val format = SimpleDateFormat("yyyy.MM.dd HH:mm")
return format.format(date)
}
fun currentTimeToLong(): Long {
return System.currentTimeMillis()
}
fun convertDateToLong(date: String): Long {
val df = SimpleDateFormat("yyyy.MM.dd HH:mm")
return df.parse(date).time
}
And to convert java file to kotlin file with Android Studio, choosing Code->Convert java file to kotlin file.
No need for anything complex:
Get current time and date as a Date object
val dateTime: Date = Calendar.getInstance().time
Convert it to a Long
val dateTimeAsLong: Long = dateTime.time
Convert that Long back to a Date
val backToDate: Date = Date(dateTimeAsLong)
I like to use extension functions, as so...
Convert long to Time & Date String:
fun Long.toTimeDateString(): String {
val dateTime = java.util.Date(this)
val format = SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US)
return format.format(dateTime)
}
Convert Time & Date String to Long:
fun String.toTimeDateLong(): Long {
val format = SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US)
return format.parse(this)?.time ?: throw IllegalArgumentException("Invalid time string")
}
To use:
fun main() {
val timeDateLong = "10:23:12 12/11/2022".toTimeDateLong()
val timeDateStr = timeDateLong.toTimeDateString()
}

Date and time in different languages

I want my app to show the German version if the phone language is German, and the English version if the phone language is English.
There is this Predefined Formats, but for the German version I don't like it.
How can I handle this?
private fun getTime(currentTime:Long): String{
val sdf = SimpleDateFormat("HH:mm")
val calendar = Calendar.getInstance()
calendar.timeInMillis = currentTime
val str = sdf.format(calendar.time)
return str
}
private fun getDate(currentTime:Long):String{
val myDate = Date()
val actualDate = myDate.time.plus(currentTime)
val myString = DateFormat.getDateInstance().format(actualDate)
return myString
}
Try using this constructor:
public SimpleDateFormat(String pattern, Locale locale)
Reference

Categories

Resources