How to find the time difference in kotlin? - android

Hello everyone I'm trying to make a small timer that will display how many minutes and seconds are left until a certain time. I want to do this using the difference between the present time and the time to which the countdown is running, but I can't figure out how to do it.
It is necessary to output the time in the format "hh:mm". That is, if now, for example, "13:27:28", and the desired time is "14:00:00", then the final result should be "32:32". And is it possible to compare time somehow? Check whether the present time is greater or less than the specified one.
import java.time.LocalTime
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
println(calculateTime("13:27:28", "14:00:00"))
}
private fun calculateTime(from: String, to: String): String {
val formatter = DateTimeFormatter.ofPattern("hh:mm:ss")
val time1 = LocalTime.parse(from, formatter)
val time2 = LocalTime.parse(to, formatter)
return time1.toString() + time2.toString()
}

Try Stopwatch from Apache Commons
val stopWatch = StopWatch().apply { start() }
...
stopWatch.stop()
println("Completed after $stopWatch")
and you get something like this: "Completed after 00:00:18.832"

Related

Filter the arraylist by subtracting with minutes in kotlin

i have an list of object , in that object i have a value timestamp and it is in "Timestamp": "2021-12-16T07:30:13.950774575Z",this format. I have a requirement when i click on a textview named 60 mins , i should get the data for 60 mins from end time , that is if i have data between 4pm to 7pm , on on click i need data from 6pm to 7pm . That is need to subtract 1 hour and filter the data, i have tried but i didn't get proper solution, can anyone help me how can it be achieved . Please help me as i am a beginner .
I would use java.time and …
parse the String received from a button click (mocked, of course)
subtract precisely one hour from the value
use the result in order to filter from an example list
Here it is, all in a fun main, read the comments, please:
fun main(args: Array<String>) {
// your example String received on button click
val timestamp = "2021-12-16T07:30:13.950774575Z"
// example values to be filtered
val someObjects = listOf(
SomeObject(0, "2021-12-12T07:30:13.950774575Z"),
SomeObject(1, "2021-12-13T07:30:13.950774575Z"),
SomeObject(2, "2021-12-13T07:30:13.950774575Z"),
SomeObject(3, "2021-12-14T07:30:13.950774575Z"),
SomeObject(4, "2021-12-15T07:30:13.950774575Z"),
// here's the border
SomeObject(5, "2021-12-16T07:30:13.850774575Z"),
SomeObject(6, "2021-12-16T07:30:13.960774575Z"),
SomeObject(7, "2021-12-17T07:30:13.950774575Z"),
SomeObject(8, "2021-12-18T07:30:13.950774575Z")
)
// parse the timestamp captured on button click and subtract an hour
val filterByOdt = OffsetDateTime.parse(timestamp).minusHours(1)
// filter the list using the OffsetDateTime
val filteredObjects = someObjects.filter {
OffsetDateTime.parse(it.timestamp)
.isBefore(filterByOdt)
}
// print the ids of the results
println(filteredObjects.joinToString(", ") { "${it.id}" })
}
I used the following dummy class in the example.
data class SomeObject(val id: Long, val timestamp: String)
As desired, the filtered list only contains the 5 SomeObjects with a timestamp before timestamp:
0, 1, 2, 3, 4
Put all your data in a list and then filter the list for the elements within the last 60 minutes.
var now = currentTS();
var l = listOf(parseTS("2021-12-16T07:30:13.950774575Z"), parseTS(...),...);
var result = l.filter { now.inMinutes() - it.inMinutes() < 60 }
I don't know which sort of timestamp class you are using, so adjust currentTS, parseTS, inMinutes to your needs.

How to use Android kotlin internal constants for formatting GPS location data

I am learning how to use Location Manager in Android kotlin to access GPS data. I currently have a simple working android app to display the current GPS position and time but the format of the data is not ideal. eg. the GPS time is displayed in milliseconds from 1st January 1970 ! I wanted to display the time of the GPS position reading in a more user friendly format along the lines of "DD/MM/YYYY HH:MM:SS". I could obviously write my own conversion routine, but I see that there are a number of android internal constants available for formatting output from the GPS sensor.
eg for GPS positions:-
FORMAT_SECONDS gives "DDD:MM:SS.SSSSS" where D indicates degrees, M indicates minutes of arc, and S indicates seconds of arc.
How can these internal constants be used to format the GPS time / GPS position?
Here is a fragment of my MainActivity.kt :-
val gps0: Long = location.time
val gps1: Double = location.latitude
val gps2: Double = location.longitude
val gps3: Float = location.accuracy
val textView0 = findViewById<TextView>(R.id.timePosn)
textView0.text = "$gps0 ms."
val textView1 = findViewById<TextView>(R.id.latitudePosn)
textView1.text = "$gps1 deg."
val textView2 = findViewById<TextView>(R.id.longitudePosn)
textView2.text = "$gps2 deg."
val textView3 = findViewById<TextView>(R.id.accuracyPosn)
textView3.text = "${gps3.toInt()} m."
I would welcome any helpful suggestions. Thanks.
You need a SimpleDateFormatter to format the date in the way you want
For example, you can do the following:
val formattedDate = formatDate(location.time);
private fun formatDate(timestampInMillis: Long): String? {
val sdf = SimpleDateFormat("MM/dd/yyyy")
return sdf.format(Date(timestampInMillis))
}
If you want to format the GPS data, you can use Location.convert()

How to compare date and time in kotlin android?

I have an app on the PlayStore and I am building a feature where the user will not see ads more than a specific number in one day.
I am thinking about comparing the current date and time to the previously saved one but haven't find a proper way to do that.
How can I compare date and time to know if 24 hours have passed or not?
Some posts that I found but not helpful:
medium.com
stackoverflow
stackoverflow
tl;dr
[This Answer uses Java syntax. You’ll have to translate to Kotlin syntax.]
if
(
Duration // Represents elapsed time on the scale of hours-minutes-seconds.
.between( // Calculates elapsed time between two points in time.
Instant.parse( "2021-03-23T15:30:57.013678Z" ) , // Last moment when an ad was show.
Instant.now() // Current moment.
) // Returns a `Duration` object.
.toHours() // Extract total number of whole hours from the `Duration` object.
>= 24L // Test if equals-to or greater-than 24 hours.
)
{ show ad }
java.time
You asked:
… know if 24 hours have passed or not?
Use the modern java.time classes defined in JSR 310. The java.time classes are built into Android 26 and later. Most of the functionality is available in earlier Android using the latest tooling’s “API desugaring“.
Instant adShown = Instant.parse( "2021-03-23T15:30:57.013678Z" ) ;
Instant now = Instant.now() ;
Duration d = Duration.between( adShown , now ) ;
long hoursSinceAdShown = d.toHours() ;
if( hoursSinceAdShown >= 24L ) { … show ad }
Record your next ad-showing as text in standard ISO 8601 format.
String output = Instant.now().toString() ;
2021-03-23T15:30:57.013678Z
Your Question asked for two different things:
Once per day
Every 24 hours
The first involves a calendar, dates, and a time zone. The second does not. I showed you code for the second.
You can use a scheduled executor service to trigger from a background thread the next showing of an ad at a specific moment. Search Stack Overflow to learn more as this has been covered many times already.
Use this code to check the current date, Yesterday or Particulardate. Pass Epoch time to this method
// input format (we get a value as Epoch)
private val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private val outputFormat = SimpleDateFormat("MMM dd")
// have to pass the time value as Epoch time.
private fun calculateDateMonth(time: String): String {
var returnValue = ""
val dateTime = DateTime((time.toLong()) * 1000L)
val inputTime = inputFormat.parse(dateTime.toString())
val convertDateMonth = outputFormat.format(inputTime!!)
val timeInMilliseconds = outputFormat.parse(convertDateMonth)!!
val mTime: Calendar = Calendar.getInstance()
mTime.setTimeInMillis(timeInMilliseconds.time)
val now = Calendar.getInstance()
returnValue = when {
now[Calendar.DATE] == mTime[Calendar.DATE] // check isToday
now[Calendar.DATE] - mTime[Calendar.DATE] == 1 // check Yesterday
else -> convertDateMonth // Month and Date
}
return returnValue
}

Trying to perform a text change in my textview at a reoccurring time on daily basis in my android project

let say i will like to automatically change my textview text at 02:00pm everyday how do I implement this functionality.
val df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
val systemDat = Calendar.getInstance(Locale.JAPAN).after(df)
if (systemDat) {
binding.includeTokyoSession.text_one.text = "successful"
} else {
binding.includeTokyoSession.text_one.text = "failure"
}
I suppose you want to change the text of your TextView after a particular time, but it seems that you're not aware of the date when comparing and you have a couple of mistakes in your code.
First, this line of code:
DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
will return a Date instance with this date and time in your local timezone 01-01-1970 02:00:00. However, you need to get a Date instance with today's date and the time 14:00:00.
Second, this line of code:
Calendar.getInstance(Locale.JAPAN).after(df)
this is a wrong usage of the Calendar::after() function, and that's because you can only pass a Calendar object to the function in order to get the right comparison result, otherwise it will always return false.
In your case you're passing a Date object.
Following is the implementation of the Calendar::after() function.
public boolean after(Object when) {
return when instanceof Calendar
&& compareTo((Calendar)when) > 0;
}
If you want to proper compare the current time today with 14:00 (comparing only the time today), here is a modification to your code:
val calendarToCompare = Calendar.getInstance(Locale.JAPAN).apply {
set(Calendar.HOUR_OF_DAY, 14)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
val systemDat = Calendar.getInstance().after(calendarToCompare)
if (systemDat) {
textview.text = "successful"
} else {
textview.text = "failure"
}
If you want to perform a lifecycle-aware view update (ex. to set the text of your textview), you can check this gist.

Showing correct sunrise/sunset times using unix timestamp

I'm getting a UNIX timestamp from DarkSkyApi for the sunrise & sunset times for the selected location and i want to convert it to a DateTime format and display it to the user. I want the time values to be local.
Example case : The user is in Italy and selects "Tokyo, JP" as the desired location to fetch weather info for. The sunrise & sunset time values should be formatted & shown as local times. So for Tokyo, sunrise should be something around 4:34 AM & 18:36 PM for sunset.
With what i have right now, i'm getting wrong values such as 12:17 for sunrise & 2:29 for sunset. Any ideas on what i'm doing wrong here?
P.S. The tmz var is the timezone of the selected location , so in this case it would be "Asia/Tokyo". Here's what i'm doing right now for the sunset time (same for the sunrise time):
private fun setViewHolderWeekDaySunsetTime(holder: ViewHolder, sunsetTime: Long, tmz: String) {
val dt = Instant.ofEpochSecond(sunsetTime).atZone(
ZoneId.of(tmz)
)
val formatted = dt.format(DateTimeFormatter.ofPattern("HH:mm"))
holder.weekDaySunsetTime.text = formatted
}
it sounds like the api is returning different time zones depending on what city you request data
So taking that into consideration, when converting the timestamp to a datetime object, you need to do something like this:
import java.time.*
val dt = Instant.ofEpochSecond(/*put time value here*/)
.atZone(/*put time zone here*/)
.toLocalDateTime() //this will convert it to your system's date time
Use this function to find timezone of every place you want with its latitude and longitude:
fun timezonecalculator(latitude:Double,longitude:Double):Double {
val resultTimeZone = TimezoneMapper.latLngToTimezoneString(latitude, longitude)
var tz= TimeZone.getTimeZone(resultTimeZone).getDisplayName(
TimeZone.getTimeZone(resultTimeZone).inDaylightTime(Date()), TimeZone.SHORT)
if ((tz=="GMT")||(tz=="UTC")||(tz=="WET"))
tz+="+00:00"
if ((tz=="CST")||(tz=="MDT"))
tz+="-06:00"
if (tz=="AST")
tz+="-04:00"
if ((tz=="EST")||(tz=="CDT"))
tz+="-05:00"
if (tz=="MST")
tz+="+05:00"
if ((tz=="CET")||(tz=="BST"))
tz+="+01:00"
if (tz=="EET")
tz+="+02:00"
if (tz=="CEST")
{tz+="+02:00"
tz=tz.drop(1)}
if (tz=="PDT")
tz+="-07:00"
if (tz=="EDT")
tz+="-04:00"
if (tz=="EEST")
{tz+="+03:00"
tz=tz.drop(1)}
if (tz=="WEST")
{tz+="+01:00"
tz=tz.drop(1)}
var sign=tz[3]
tz=tz.drop(4)
val minute=tz.drop(3)
val hour=tz.dropLast(3)
val min=Integer.parseInt(minute)
val hou=Integer.parseInt(hour)
var timezone=hou+(min.toDouble()/60)
if (sign=='-')
timezone*=-1
return timezone
}
And TimeZoneMapper class is https://raw.githubusercontent.com/drtimcooper/LatLongToTimezone/master/src/main/java/com/skedgo/converter/TimezoneMapper.java
See here to know how to use this class: https://github.com/drtimcooper/LatLongToTimezone
You invoke it this way: timezonecalculator(latitude, longitude)
Example: timezonecalculator(36.2, 59.6)
Output: 4.5

Categories

Resources