Time with flutter - flutter

I am totally new with flutter and I do not understand how can I resolve a problem.
I'm actually working to a kart race app and:
I need to read a string like 1:02.456
Convert in some kind of time
Compare with another string similar to first one
Go to do something
es:
blap = null;
if(1:02.456 < 1:03.589){
blap = '1:02.456';
} else {
blap = '1:03.589;
}
I read on the web that I ca use the class DateTime, but every time I try to convert the string in an object of that class, I do not get wat I want.
There is a better way?
Thank you.

If you are working on a kart race app probably you need to use Duration, not DateTime.
This is one way to convert a string like yours into Duration
Duration parseDuration(String s) {
int hours = 0;
int minutes = 0;
int micros;
List<String> parts = s.split(':');
if (parts.length > 2) {
hours = int.parse(parts[parts.length - 3]);
}
if (parts.length > 1) {
minutes = int.parse(parts[parts.length - 2]);
}
micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
return Duration(hours: hours, minutes: minutes, microseconds: micros);
}
Then, to compare two Duration in the way you wanted, this is an example:
String blap;
Duration time1=Duration(hours: 1),time2=Duration(hours: 2);
if(time1.compareTo(time2)<0){
//time2 is greater than time1
blap=time1.toString();
}else{
blap=time2.toString();
}

Related

How to convert the current time to seconds? in Flutter?

I have two methods, one method with which I get the current time in milliseconds and the second method I get how much time I need to go to the store in seconds. But I need to subtract (current time) - (drive time to the store), for this I need to convert the current time to seconds, tell me how to do this?
here i get the current time
void getTimeNow() {
var ms = (DateTime.now()).millisecondsSinceEpoch;
var time = (ms / 1000).round();
}
here I get the travel time to the shop in seconds
String getTimeToStation (DirectionModel? directionModel) {
double duration = -1;
if (directionModel != null &&
directionModel.routes[0].summary.travelTimeInSeconds != null) {
duration = directionModel.routes[0].summary.travelTimeInSeconds / 60;
}
return duration != -1 ? '${duration.toStringAsFixed(1)} h' : '';
}
You can subtract time like
final currentTime = DateTime.now();
Duration driveTimeToStore = Duration(seconds: 4);
final DateTime driveBeginTime = currentTime.subtract(driveTimeToStore);

How to make a live counter in unity3d

I recently started using Unity3D and made a few levels. The only problem I have right now is how can I get a live counter?
So my character dies when he hits and certain object.
I want my character to get 3 lives maximum, and get -1 live when he hits that object.
And that it keeps the data when he dies so you wouldn't get lives back if you restart the app.
And after a certain amount of minutes he gets +1 live.
Thank you :)
While your game running. just create a variable counterTime to count time, whenever counterTime pass certain amount of time you want reset counterTime to 0 and increase your life.
When user quit your app, save last time to PlayerPref, eg:
PlayerPref.SaveString("LastTime", DateTime.Now);
When user comback game, just check duration between last time and now to calculate total life need added. eg:
DateTime lastTime = DateTime.Parse(PlayerPref.GetString("LastTime"));
TimeSpan timeDif= DateTime.Now - lastTime;
int duration = timeDif.TotalSeconds;
You can use PlayerPrefs.SetInt , PlayerPrefs.GetInt for storing and reading your player's hp in file storage. Read more about it here:
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
As for Giving player +1 hp after a few minutes you can store DateTime.Now in a PlayerPrefs variable whenever you give your player some hp and use TimeSpan and TotalMinutesPassed:
TimeSpan passedTime = DateTime.Now - lastStoredDateTime;
int totalMinutesPassed = passedTime.TotalMinutes;
Should go sth like this i guess(didnt test this code just showing a general idea) :
void SetPlayerLives(int lives)
{
playerLives = lives;
PlayerPrefs.SetInt("player-lives",playerLives);
}
//TODO: also sth like => int GetPlayerLives() function
void CheckLiveRegen() //call this function whenever you want to check live regen:
{
int LIVE_REGEN_MINUTES = 5; //regen 1 live every 5 minutes
DateTime lastStoredDateTime = DateTime.Parse(PlayerPrefs.GetString("last-live-regen", DateTime.Now.ToString()));
TimeSpan passedTime = DateTime.Now - lastStoredDateTime;
double totalMinutesPassed = passedTime.TotalMinutes;
if(totalMinutesPassed >= LIVE_REGEN_MINUTES)
{
int val = (int) totalMinutesPassed / LIVE_REGEN_MINUTES;
// Add val to your player lives! + store new lives value
SetPlayerLives(playerLives+val);
//update last-live-regen value:
PlayerPrefs.SetString("last-live-regen", DateTime.Now.ToString());
}
}
Note: DateTime , TimeSpan classes have some bugs (specially in android platform) in versions older than 2017.4 (LTS) Make sure you log values and check if functions are working properly.
https://forum.unity.com/threads/android-datetime-now-is-wrong.488380/
check out the following link to understand how to create a life counter in unity
http://codesaying.com/life-counter-in-unity/
In order to calculate the time that was lapsed since you last shut down the game, you should save the last time playerprefs in the function OnApplicationPause and calcuate the timelapsed in the Awake Function.
void Awake () {
if(!PlayerPrefs.HasKey("Lives")){
PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.ToString());
}
lives = PlayerPrefs.GetInt("Lives", maxLives);
//update life counter only if lives are less than maxLives
if (lives < maxLives)
{
float timerToAdd = (float)(System.DateTime.Now - Convert.ToDateTime(PlayerPrefs.GetString("LifeUpdateTime"))).TotalSeconds;
UpdateLives(timerToAdd);
}
}
void UpdateLives(double timerToAdd ){
if (lives < maxLives)
{
int livesToAdd = Mathf.FloorToInt((float)timerToAdd / lifeReplenishTime);
timerForLife = (float)timerToAdd % lifeReplenishTime;
lives += livesToAdd;
if (lives > maxLives)
{
lives = maxLives;
timerForLife = 0;
}
PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.AddSeconds(-timerForLife).ToString());
}else{
PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.ToString());
}
}
void OnApplicationPause(bool isPause)
{
if (isPause)
{
timeOfPause = System.DateTime.Now;
}
else
{
if(timeOfPause == default(DateTime)){
timeOfPause = System.DateTime.Now;
}
float timerToAdd = (float)(System.DateTime.Now - timeOfPause).TotalSeconds;
timerForLife += timerToAdd;
UpdateLives(timerForLife);
}
}
}

Comparing only dates of DateTimes in Dart

I need to store and compare dates (without times) in my app, without caring about time zones.
I can see three solutions to this:
(date1.year == date2.year && date1.month == date2.month && date1.day == date2.day)
This is what I'm doing now, but it's horrible verbose.
date1.format("YYYYMMDD") == date2.format("YYYYMMDD")
This is still rather verbose (though not as bad), but just seems inefficient to me...
Create a new Date class myself, perhaps storing the date as a "YYYYMMDD" string, or number of days since Jan 1 1980. But this means re-implementing a whole bunch of complex logic like different month lengths, adding/subtracting and leap years.
Creating a new class also avoids an edge case I'm worried about, where adding Duration(days: 1) ends up with the same date due to daylight saving changes. But there are probably edge cases with this method I'm not thinking of...
Which is the best of these solutions, or is there an even better solution I haven't thought of?
Since I asked this, extension methods have been released in Dart. I would now implement option 1 as an extension method:
extension DateOnlyCompare on DateTime {
bool isSameDate(DateTime other) {
return year == other.year && month == other.month
&& day == other.day;
}
}
You can use compareTo:
var temp = DateTime.now().toUtc();
var d1 = DateTime.utc(temp.year,temp.month,temp.day);
var d2 = DateTime.utc(2018,10,25); //you can add today's date here
if(d2.compareTo(d1)==0){
print('true');
}else{
print('false');
}
DateTime dateTime = DateTime.now();
DateTime _pickedDate = // Some other DateTime instance
dateTime.difference(_pickedDate).inDays == 0 // <- this results to true or false
Because difference() method of DateTime return results as Duration() object, we can simply compare days only by converting Duration into days using inDays property
The easiest option is just to use DateUtils
For example
if (DateUtils.isSameDay(date1, date2){
print('same day')
}
isSameDay takes in 2 DateTime objects and ignores the time element
I am using this function to calculate the difference in days.
Comparing dates is tricky as the result depends not just on the timestamps but also the timezone of the user.
int diffInDays (DateTime date1, DateTime date2) {
return ((date1.difference(date2) - Duration(hours: date1.hour) + Duration(hours: date2.hour)).inHours / 24).round();
}
Use instead the package: dart_date
Dart Extensions for DartTime
dart_date provides the most comprehensive, yet simple and consistent toolset for manipulating Dart dates.
dart_date
DateTime now = DateTime.now();
DateTime date = ....;
if (date.isSameDay(now)) {
//....
} else {
//....
}
Also here the difference in days :
int differenceInDays(DateTime a, DateTime b) => a.differenceInDays(b);
Use isAtSameMomentAs:
var date1 = DateTime.now();
var date2 = date1.add(Duration(seconds: 1));
var isSame = date1.isAtSameMomentAs(date2); // false

JasperSoft Studio - How is the best way to to print a period of time (minutes) as hh:mm? [duplicate]

I need to convert minutes to hours and minutes in java. For example 260 minutes should be 4:20. can anyone help me how to do convert it.
If your time is in a variable called t
int hours = t / 60; //since both are ints, you get an int
int minutes = t % 60;
System.out.printf("%d:%02d", hours, minutes);
It couldn't get easier
Addendum from 2021:
Please notice that this answer is about the literal meaning of the question: how to convert an amount of minute to hours + minutes. It has nothing to do with time, time zones, AM/PM...
If you need better control about this kind of stuff, i.e. you're dealing with moments in time and not just an amount of minutes and hours, see Basil Bourque's answer below.
tl;dr
Duration.ofMinutes( 260L )
.toString()
PT4H20M
… or …
LocalTime.MIN.plus(
Duration.ofMinutes( 260L )
).toString()
04:20
Duration
The java.time classes include a pair of classes to represent spans of time. The Duration class is for hours-minutes-seconds, and Period is for years-months-days.
Duration d = Duration.ofMinutes( 260L );
Duration parts
Access each part of the Duration by calling to…Part. These methods were added in Java 9 and later.
long days = d.toDaysPart() ;
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;
int nanos = d.toNanosPart() ;
You can then assemble your own string from those parts.
ISO 8601
The ISO 8601 standard defines textual formats for date-time values. For spans of time unattached to the timeline, the standard format is PnYnMnDTnHnMnS. The P marks the beginning, and the T separates the years-month-days from the hours-minutes-seconds. So an hour and a half is PT1H30M.
The java.time classes use ISO 8601 formats by default for parsing and generating strings. The Duration and Period classes use this particular standard format. So simply call toString.
String output = d.toString();
PT4H20M
For alternate formatting, build your own String in Java 9 and later (not in Java 8) with the Duration::to…Part methods. Or see this Answer for using regex to manipulate the ISO 8601 formatted string.
LocalTime
I strongly suggest using the standard ISO 8601 format instead of the extremely ambiguous and confusing clock format of 04:20. But if you insist, you can get this effect by hacking with the LocalTime class. This works if your duration is not over 24 hours.
LocalTime hackUseOfClockAsDuration = LocalTime.MIN.plus( d );
String output = hackUseOfClockAsDuration.toString();
04:20
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Use java.text.SimpleDateFormat to convert minute into hours and minute
SimpleDateFormat sdf = new SimpleDateFormat("mm");
try {
Date dt = sdf.parse("90");
sdf = new SimpleDateFormat("HH:mm");
System.out.println(sdf.format(dt));
} catch (ParseException e) {
e.printStackTrace();
}
You can also use the TimeUnit class. You could define private static final String FORMAT = "%02d:%02d:%02d";
can have a method like:
public static String parseTime(long milliseconds) {
return String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(milliseconds),
TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(milliseconds)),
TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(milliseconds)));
}
I use this function for my projects:
public static String minuteToTime(int minute) {
int hour = minute / 60;
minute %= 60;
String p = "AM";
if (hour >= 12) {
hour %= 12;
p = "PM";
}
if (hour == 0) {
hour = 12;
}
return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + " " + p;
}
It can be done like this
int totalMinutesInt = Integer.valueOf(totalMinutes.toString());
int hours = totalMinutesInt / 60;
int hoursToDisplay = hours;
if (hours > 12) {
hoursToDisplay = hoursToDisplay - 12;
}
int minutesToDisplay = totalMinutesInt - (hours * 60);
String minToDisplay = null;
if(minutesToDisplay == 0 ) minToDisplay = "00";
else if( minutesToDisplay < 10 ) minToDisplay = "0" + minutesToDisplay ;
else minToDisplay = "" + minutesToDisplay ;
String displayValue = hoursToDisplay + ":" + minToDisplay;
if (hours < 12)
displayValue = displayValue + " AM";
else
displayValue = displayValue + " PM";
return displayValue;
} catch (Exception e) {
LOGGER.error("Error while converting currency.");
}
return totalMinutes.toString();
(In Kotlin) If you are going to put the answer into a TextView or something you can instead use a string resource:
<string name="time">%02d:%02d</string>
And then you can use this String resource to then set the text at run time using:
private fun setTime(time: Int) {
val hour = time / 60
val min = time % 60
main_time.text = getString(R.string.time, hour, min)
}
Given input in seconds you can transform to format hh:mm:ss like this :
int hours;
int minutes;
int seconds;
int formatHelper;
int input;
//formatHelper maximum value is 24 hours represented in seconds
formatHelper = input % (24*60*60);
//for example let's say format helper is 7500 seconds
hours = formatHelper/60*60;
minutes = formatHelper/60%60;
seconds = formatHelper%60;
//now operations above will give you result = 2hours : 5 minutes : 0 seconds;
I have used formatHelper since the input can be more then 86 400 seconds, which is 24 hours.
If you want total time of your input represented by hh:mm:ss, you can just avoid formatHelper.
I hope it helps.
Here is my function for convert a second,millisecond to day,hour,minute,second
public static String millisecondToFullTime(long millisecond) {
return timeUnitToFullTime(millisecond, TimeUnit.MILLISECONDS);
}
public static String secondToFullTime(long second) {
return timeUnitToFullTime(second, TimeUnit.SECONDS);
}
public static String timeUnitToFullTime(long time, TimeUnit timeUnit) {
long day = timeUnit.toDays(time);
long hour = timeUnit.toHours(time) % 24;
long minute = timeUnit.toMinutes(time) % 60;
long second = timeUnit.toSeconds(time) % 60;
if (day > 0) {
return String.format("%dday %02d:%02d:%02d", day, hour, minute, second);
} else if (hour > 0) {
return String.format("%d:%02d:%02d", hour, minute, second);
} else if (minute > 0) {
return String.format("%d:%02d", minute, second);
} else {
return String.format("%02d", second);
}
}
Testing
public static void main(String[] args) {
System.out.println("60 => " + secondToFullTime(60));
System.out.println("101 => " + secondToFullTime(101));
System.out.println("601 => " + secondToFullTime(601));
System.out.println("7601 => " + secondToFullTime(7601));
System.out.println("36001 => " + secondToFullTime(36001));
System.out.println("86401 => " + secondToFullTime(86401));
}
Output
60 => 1:00
101 => 1:41
601 => 10:01
7601 => 2:06:41
36001 => 10:00:01
86401 => 1day 00:00:01
Hope it help
Minutes mod 60 will gives hours with minutes remaining.
http://www.cafeaulait.org/course/week2/15.html
int mHours = t / 60; //since both are ints, you get an int
int mMinutes = t % 60;
System.out.printf("%d:%02d", "" +mHours, "" +mMinutes);
Solution on kotlin Documentation
import kotlin.time.Duration
import kotlin.time.DurationUnit
import kotlin.time.toDuration
val min = 150.toDuration(DurationUnit.MINUTES)
val time = min.toComponents { days, hours, minutes, seconds, nanoseconds ->
"$days $hours $minutes $seconds $nanoseconds"
}
We get 0 days 2 hours 30 minutes 0 seconds 0 nanoseconds
We can also use
DurationUnit.DAYS
DurationUnit.HOURS
DurationUnit.SECONDS
DurationUnit.MILLISECONDS
DurationUnit.MICROSECONDS
DurationUnit.NANOSECONDS
long d1Ms=asa.getTime();
long d2Ms=asa2.getTime();
long minute = Math.abs((d1Ms-d2Ms)/60000);
int Hours = (int)minute/60;
int Minutes = (int)minute%60;
stUr.setText(Hours+":"+Minutes);
Try this code:
import java.util.Scanner;
public class BasicElement {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int hours;
System.out.print("Enter the hours to convert:");
hours =input.nextInt();
int d=hours/24;
int m=hours%24;
System.out.println(d+"days"+" "+m+"hours");
}
}
import java.util.Scanner;
public class Time{
public static void main(String[]args){
int totMins=0;
int hours=0;
int mins=0;
Scanner sc= new Scanner(System.in);
System.out.println("Enter the time in mins: ");
totMins= sc.nextInt();
hours=(int)(totMins/60);
mins =(int)(totMins%60);
System.out.printf("%d:%d",hours,mins);
}
}

Can the below function be improve?(C#3.0)

I have the below function
public static List<DateTime> GetOnlyFridays(DateTime endDate, int weeks, bool isIncludeBaseDate)
{
//Get only the fridays from the date range
List<DateTime> dtlist = new List<DateTime>();
List<DateTime> tempDtlist = (from dtFridays in GetDates(endDate, weeks)
where dtFridays.DayOfWeek == DayOfWeek.Friday
select dtFridays).ToList();
if (isIncludeBaseDate)
{
dtlist = tempDtlist.Skip(1).ToList();
dtlist.Add(endDate);
}
else
{
dtlist = tempDtlist;
}
return dtlist;
}
What basically I am doing is getting the datelist using the GetDates function and then depending on the isIncludeBaseDate bool value(if true) skipping the last date and adding the Base Date
It is working fine but can this program can be improve?
I am using C#3.0 and Framework 3.5
Thanks
You're doing too many temporary list-conversions; you can keep all the work as a query until the very end, that way it'll only be evaluated once.
public static List<DateTime> GetOnlyFridays(DateTime endDate, int weeks, bool isIncludeBaseDate)
{
var fridays = GetDates(endDate, weeks)
.Where(d => d.DayOfWeek == DayOfWeek.Friday);
if (isIncludeBaseDate)
{
fridays = fridays.Skip(1)
.Concat(new []{endDate});
}
return fridays.ToList();
}
You don't need to convert to a list immediately. For example, the following should work just as well, but without the need to convert the result to a list (it allows you to loop over them in a foreach loop, for example, without ever having to instantiate an entire list. If you pass in a large number for weeks that could be a big saving in terms of memory usage):
public static IEnumerable<DateTime> GetOnlyFridays(DateTime endDate, int weeks, bool isIncludeBaseDate)
{
var fridays = from dtFridays in GetDates(endDate, weeks)
where dtFridays.DayOfWeek == DayOfWeek.Friday
select dtFridays;
if (isIncludeBaseDate)
{
return fridays.Skip(1);
}
return fridays;
}
I would also try finding the closest friday at or before 'endDate', then for as many weeks we have, do a DateTime.AddDays(7); and of course take into consideration isIncludeBaseDate.