Android Joda-Time with Kotlin - android

I am trying to create a function to check a given string time HH:mm is in range of another comparing to now.
Example: if the current hour is between 12:35 and 15:00 return true
But I always got false even if the current time is in range..
fun isTimeInRange(before: String, after: String): Boolean {
val now = DateTime.now()
val format = DateTimeFormat.forPattern("HH:mm")
return now >= DateTime.parse(before, format) && now <= DateTime.parse(after, format)
}

You need to do:
fun isTimeInRange(before: String, after: String): Boolean {
val now = DateTime.now()
val format = DateTimeFormat.forPattern("HH:mm")
return now.isAfter(DateTime.parse(before, format)) && now.isBefore(DateTime.parse(after, format))
}
Or use intervals.

You have to set before/after date to today's date. try this:
fun isTimeInRange(start: String, end: String): Boolean {
val now = DateTime.now()
val format = DateTimeFormat.forPattern("HH:mm")
val startTime: LocalTime = format.parseLocalTime(start)
val endTime: LocalTime = format.parseLocalTime(end)
val timeZone = DateTimeZone.getDefault()
val today: LocalDate = LocalDate.now(timeZone)
val startMoment: DateTime = today.toLocalDateTime(startTime).toDateTime(timeZone)
val endMoment: DateTime = today.toLocalDateTime(endTime).toDateTime(timeZone)
return now.isAfter(startMoment) && now.isBefore(endMoment)
}

Related

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
}
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.

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 to get current date and time in ISO 8601 format in kotlin?

I am trying to get the current date and time in ISO 8601 format. My code below returns the date 14 days later and incorrect time. I need the correct format and current date for an api request.
val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").apply {
this.timeZone = TimeZone.getTimeZone("CST")
}
val now = Calendar.getInstance(TimeZone.getTimeZone("CST"))
val sendDateUAT = formatter.format(now.time)
Log.d(TAG, "sendDate: $sendDateUAT")
This returns: 2019-08-05T02:53:40Z
EDIT: This is now.time:
java.util.GregorianCalendar[time=1564973620006,areFieldsSet=true,lenient=true,zone=GMT,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=7,WEEK_OF_YEAR=32,WEEK_OF_MONTH=2,DAY_OF_MONTH=5,DAY_OF_YEAR=217,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=2,HOUR_OF_DAY=2,MINUTE=53,SECOND=40,MILLISECOND=6,ZONE_OFFSET=0,DST_OFFSET=0]
Here is a helper class that you can use to convert your dates:
public object DateHelper {
private const val ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
#JvmName("toIsoStringNullable")
fun Date?.toIsoString(): String? {
return this?.toIsoString()
}
fun Date.toIsoString(): String {
val dateFormat: DateFormat = SimpleDateFormat(ISO_8601_24H_FULL_FORMAT)
return dateFormat.format(this)
}
}
It can be used very concisely like this:
Date().toIsoString()
For some reason this fixed the problem and returned the correct date.
val today = Calendar.getInstance()
val sendDateUAT = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(today.time)

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()
}

How to get current local date and time in Kotlin

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.

Categories

Resources