iOS view similar to Chronometer on Android - android

On Android there exists a standard view called Chronometer details here. Does iOS have a similar view or a library that does something similar?

I not found anyway todo this, so i create a gist here with GPL license, if someone get excited to make it a lib :)

I would use an Timer for this.
var timer = Timer()
timer = Timer(timeInterval: 0.01, target: self, selector: #selector(update), userInfo: nil, repeats: false)
#IBAction func start(sender: UIButton) {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update(_:)), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
startTime = Date() // new instance variable that you would need to add.
}
func update() {
let elapsedTime = Date().timeIntervalSince(startTime)
let currTime = totalTime - elapsedTime
//total time is an instance variable that is the total amount of time in seconds that you want
countDown.text = String(currTime)
if currTime < 0 {
timer.invalidate()
//do other stuff that you need to do when time runs out.
}
}
If you want a smaller or larger pieces of time, just change it the Interval parameter.
Also you still would have to address creating some logic to split minutes / seconds ect. using Date methods and incrementing some instance variable.

Why not use a UIDatePicker in timer mode?
UIDatePicker* datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 206)];
datePicker.datePickerMode = UIDatePickerModeCountDownTimer;
datePicker.countDownDuration = 60*5;
[self.view addSubview:datePicker];

Related

How to find the time difference in kotlin?

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"

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
}

How to create timer with handler

Need to create stopwatch in android, for now I'v got somethink like this, simple function to start counting and display time, but i dont know what am I doing wrong with postdelayed:
fun runTimer() {
val timeView = findViewById<TextView>(R.id.time_view)
val handler = Handler()
handler.post(Runnable {
var hours = seconds / 3600
var minutes = (seconds % 3600) / 60
var secs = seconds % 60
var time = String.format("%d:%02d:%02d", hours, minutes, secs)
timeView.setText(time)
if (running) {
seconds++
}
handler.postDelayed(this, 1000)
})
}
what exactly should i put instead of this? (need to be runnable type)
I believe in your use case the most suitable solution would be to use a Chronometer - you can read more about it here. Also if you want to watch a video tutorial you can check this video. Hope this helps. Additionally if you want to have the functionality to be able to set a specific time frame and countdown using a CountDownTimer is a good option - documentation
I use handler as Timer like this :
class TimerClass {
fun startTimer( handler : Handler ,
stuffToDo : () -> Unit ,
stopTimeInSeconds : Int ,
timePassed : Int ,
interval : Long){
handler.postDelayed( {
stuffToDo.invoke()
if (timePassed < stopTimeInSeconds){
startTimer(handler ,
stuffToDo ,
stopTimeInSeconds ,
timePassed + 1 ,
interval)
}
} , interval)
}}
then to use it :
val time = TestClass()
time.startTimer(handler = Handler() ,
stuffToDo = { textView.text = "some new text" } ,
stopTimeInSeconds = 5 ,
timePassed = 0 ,
interval = 1000)
So you define a method in the class , and provide all dependencies(objects) and injecting to it, you are creating the operation you want to do as a lambda function. then call the handler delayed method and in the handler if the criteria (if statement) is true you will call the method itself recursively with an increment (timePassed+1).
Now you have a working timer.

Titanium Change event not firing the first time with picker

I am making an iOS and Android app using Titanium Classic. I am fairly new to Titanium but I have some experience using Javascript. The app will have a window where the user and select from a picker an amount of time in hours and minutes. The selection will be saved and be used later to send a notification to the user that the time they selected is up. I am currently using Titanium's picker function with the type of "count down timer." However, I am having trouble getting the change event to work when the user selects a different time. It also will show the last selected time when I try going to a different window and entering the timer window again.
My question is how can I get the change event to fire the first time the user selects a different number?
In follow up to my question, is there a better way to save the picker selection for later use?
Here is the code for the picker:
var hours = 0;
var minutes = 1;
var win = Ti.UI.createWindow({
backgroundColor: '#A6B97B',
layout: 'horizontal'
});
var picker = Ti.UI.createPicker({
type:Ti.UI.PICKER_TYPE_COUNT_DOWN_TIMER,
top:2,
width: '50%',
height: '20%'
});
picker.addEventListener("change", function(e) {
Ti.App.Properties.setInt('countDownDuration', e.countDownDuration);
if (e.countDownDuration >= 3600000)
{
hours = Math.floor(Ti.App.Properties.getInt('countDownDuration')/3600000);
minutes = Math.floor(Ti.App.Properties.getInt('countDownDuration')/60000 - (hours*60));
}
else {
minutes = Math.floor(Ti.App.Properties.getInt('countDownDuration')/60000);
hours = 0;
}
});
var doneBtn = Ti.UI.createButton({
title : 'Get Value',
height : '15%',
width : '30%'
});
doneBtn.addEventListener('click', function() {
// get value
if(hours > 0){
alert('You set the time estimate to ' + hours + ' hours and ' + minutes+ ' minutes');
}
else {
alert('You set the time estimate to ' + minutes + ' minutes');
}
});
If anyone has any advice on how to get the change event to fire the first time, I would really appreciate it. Also, if you know a better way to accomplish saving data from the picker for use later, that would be helpful as well.
Thanks!
Jessica

Is there a preferred way to get the system time in cocos2d-x?

I am writing a cross-platform application in Cocos2d-x. I need to get the time to create a countdown clock to a certain time of day. Since it is in C++, I can use time(...), mktime(...), and difftime(...) if I need to as a direct approach.
Is there a preferred method in Cocos2d-x for doing this in a cross-platform way (i.e. something built directly into the framework)? I want the app to work the same on iPhones, iPads, and Android.
try this:
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
CCLog("year------->%04d",timeinfo->tm_year+1900);
CCLog("month------->%02d",timeinfo->tm_mon+1);
CCLog("day------->%02d",timeinfo->tm_mday);
CCLog("hour------->%02d",timeinfo->tm_hour);
CCLog("minutes------->%02d",timeinfo->tm_min);
CCLog("seconds------->%02d",timeinfo->tm_sec);
Try this code
static inline long millisecondNow()
{
struct cc_timeval now;
CCTime::gettimeofdayCocos2d(&now, NULL);
return (now.tv_sec * 1000 + now.tv_usec / 1000);
}
I used this function to get current time in millisecond. I am new in cocos2d-x so hope this can be helpful.
You should try this lib, I just tested and it works fine.
https://github.com/Ghost233/CCDate
If you receive some wrong values, set timezoneOffset = 0;
Note: 0 <= month <= 11
You can sheduleUpdate in clock class.
The update call with a float argument which is a delta time in seconds after last calls, this method is called every frame and cocos2d-x get time through from the system and count the delta.
I thought this code would do the trick:
static inline long millisecondNow()
{
struct cc_timeval now;
CCTime::gettimeofdayCocos2d(&now, NULL);
return (now.tv_sec * 1000 + now.tv_usec / 1000);
}
HOWEVER, only gives a part of what I need. In general, I need a real "date and time" object (or structure), not just the time of day in milliseconds.
The best solution, for now, seems to be using the "classic" localtime, mktime, difftime trifecta in C++. I have a few examples below of some basic operations...I may cook up a general class to do these kinds of operations, but for now, these are a good start and show how to get moving:
double Utilities::SecondsTill(int hour, int minute)
{
time_t now;
struct tm target;
double seconds;
time(&now);
target = *localtime(&now);
target.tm_hour = hour;
target.tm_min = minute;
target.tm_sec = 0;
seconds = difftime(mktime(&target),now);
return seconds;
}
DAYS_OF_WEEK_T Utilities::GetDayOfWeek()
{
struct tm tinfo;
time_t rawtime;
time (&rawtime);
tinfo = *localtime(&rawtime);
return (DAYS_OF_WEEK_T)tinfo.tm_wday;
}

Categories

Resources