Time of the day in minutes Java - java

I am looking to calculate the number of minutes given the time of the day.
Eg.: when input is 11:34, the output should be 11*60+34. The date doesn't matter.
I only need it down to the minutes scale. Seconds, milliseconds... don't matter.
Is there a method somewhere in Java doing this the neat way without me calculating it?
Right now, i'm using theTime.split(":"), theTime is a String holding "11:34" here, parsing the integers on each side and doing the calculation.
I saw Time but what I'm doing right now seemed more direct.
Nothing in Systems either.

There is no build in method for it. However here is a one-liner for it:
int timeInMins = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) * 60 + Calendar.getInstance().get(Calendar.MINUTE);

Your approach looks good and sound, however to answer your question it would be simple to say that there is no such build in method which does that. You have to calculate it the way you are doing it right now.

Hi maybe you could use JodaTime? Below example how to get number of minutes from parsed string and from current time. In java 8 there is similar api but I haven't found exactly method like minutesOfDay()
#Test
public void learnHowManyMinutesPassedToday() {
DateTime time = DateTimeFormat.forPattern("HH:mm").parseDateTime("11:34");
System.out.println(time.getMinuteOfDay());
System.out.println(DateTime.now().getMinuteOfDay());
}

If you are looking to have input not from a String, take a look at
Java.util.Calendar.
It has Calendar.HOUR_OF_DAY and Calendar.HOUR and Calendar.MINUTE which could be your input. I'm not sure what the "neat" way of doing this would be. It is a simple calculation.

Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR);
int min = rightNow.get(Calendar.MINUTE);
System.out.println("TimeMinutes:" + hour * 60 + min);
EDIT:
Except using split use the above.

Related

Java: addToDay function

I'm trying to setup my addToDay function. I'm currently stuck on how to proceed with this or even write it correctly. The function itself will take a variable that ranges from -100 to 100. So you would basically add that variable to the current and if it was below the 0 then subtract a month or if it was above the months max day then add a month. Which i have that function setup so all i would have to do is call addToMonth with the correct amount. My problem lies within the amount of days each month has. For example, October has 31 days while November has 30. I have a function that will return the number of days in the current set month so i can call that to get how many max days should be in the current month. I'm thinking maybe a while loop would work but i just wanted to get anyone's thoughts on the best way to set it up.
I have 3 private ints: month, day, year. These are what need to be changed. I have both addTo functions for month and year setup already.
Here are some other functions i have created that can be used in this:
1. addToMonth(int delta) - changes the current month depending on the given parameter
2. getDaysInMonth() - will return the days in a month depending on the month itself
3. validateDay() - Will return true or false if the days fall outside the wanted requirements.
I don't want to use the calendar utility
I also don't want to use any other utilities. Just the base code with Junit for testing
Joda's plusDays() function and Java 8 LocalDate already has the logic that you are trying to achieve
Alright so i ended up just copying my original addToMonth function and modifying it abit to fit with days. So far it works but i do think it'll fail in the cases of different amounth of days not lining up.

How to set Chronometer in milliseconds (MM:SS:mm)

I have a chronometer used as a timer in a game. Currently it only shows seconds (by default). I have been trying to get the format to show in minutes:seconds:milliseconds. I tried but nothing is working. Here is the code I found on StackoverFlow that says it should work...but didn't. OR if you have any other solutions instead of chronometer please let me know! (This is in android, using java)
-Thanks
Chronometer chronometer;
chronometer.setFormat(MM:SS:mm);
Actually, there's a much nicer way of doing this:
void OnGUI() {
int minutes = Mathf.FloorToInt(timer / 60F);
int seconds = Mathf.FloorToInt(timer - minutes * 60);
string niceTime = string.Format("{0:0}:{1:00}", minutes, seconds);
GUI.Label(new Rect(10,10,250,100), niceTime);
}
This will give you times in the 0:00 format. If you'd rather have 00:00, simply do
string niceTime = string.Format("{0:00}:{1:00}", minutes, seconds);
There's a couple of possibilities you have with the formats here: {0:#.00} would give you something like 3.00 or 10.12 or 123.45. For stuff like scores, you might want something like {0:00000} which would give you 00001 or 02523 or 20000 (or 2000000 if that's your score ;-) ). Basically, the formatting part allows any kind of formatting (so you can also use this to format date times and other complex types). Basically, this means {indexOfParameter:formatting}

How to convert NSDate to integer to pass PHP date() as unix timestamp?

I'm an objective-c beginner and I was assigned to create an iPhone app for our client. I have some background with Java but almost no experience in this objective-c and this is my first time to developping a complete application...
Anyway, I'm currently stack at several problems. One of those problem is that I need to send an integer value for PHP's date function from my iOS app. I've been searching around for the solution, but all of them are dealing with opposite ways (int to NSDate), not NSDate to integer value.
I tried solutions like answered here
but it's obvious it returns double, not an integer...
Or this
but this couldn't get the System time.
I know I could get current system's NSDate with:
NSDate *theDay = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone systemTimeZone] secondsFromGMT]];
But I could not figure out how to convert this to an integer (or long) value.
I just need to get the same value as we can get in Java with System.currentTimeMillis().
Also, this is my first time to ask questions here in stackoverflow. So please let me know if there's anything I should do/not to do when posting questions here, etc.
Thank you.
To get the current date, you should use this:
NSDate *theDate = [NSDate date];
To get it in seconds since January 1st, 1970, as a double, you would use:
NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
To get it in ms, simply multiply the previous value by 1000 and let the compiler cast it into an integer without needing any additional code:
long long milliseconds = [[NSDate date] timeIntervalSince1970] * 1000;
And as #HotLicks points out, while System.currentTimeMillis() is in GMT, if you need the local time, you could use:
long long milliseconds = ([[NSDate date] timeIntervalSince1970]
+ [[NSTimeZone defaultTimeZone] secondsFromGMT]) * 1000;
(I think that most web services will want GMT though.)

java calculate time between two timestamps

I need to calculate the time passed between two dates.
The catch here is that I need to show it as YouTube does with its video comments timestamps. That is, to show it by just the largest measure.
For example,
if the time is 50 seconds ago it should say 50 seconds ago.
if the time is more than one minute it should say one minute ago/ten minutes ago etc..
if the time difference is 1 hour 30 mins it should show: an hour ago.
if the time is one and a half week than it should say one week ago.
if the time is more than a month it should say one month ago/two months ago etc...
and so on and so on..
So what is the best way to handle this?
Should I make a method with case or if statements that would return something like this? Or is there a better approach (maybe a library which already does something like it)?
Use DateUtils.getRelativeTimeSpanString(long time, long now, long minResolution). time is the start time, and now is the end time (in milliseconds). To report "seconds ago," set minResolution to zero.
Example:
String result = DateUtils.getRelativeTimeSpanString(1306767830, 1306767835, 0);
// result = "5 seconds ago"
date1.getTime() - date2.getTime()
This will return you the time in miliseconds between the 2 dates. Just convert that to what ever you want to show (e.g. hours minutes seconds)
On Android, use this: http://developer.android.com/reference/android/text/format/DateUtils.html#getRelativeTimeSpanString%28android.content.Context,%20long,%20boolean%29
Take a look at PrettyTime!
Also, everytime you want to do something date/time-related in Java, you should take a look at Joda Time. Do it now, you will thank me later.
Your need is very specific, and I don't know any lib that would solve the problem for you out of the box.
However the problem is not very complex and a small function full of "ifs" should do the trick.
Of course, a nice date library like Joda Time will help you keep your code clean. Who wants to use GregorianCalendar!?
Looks like you have a set of custom rules and the algorithm to choose a rule is based on the time in seconds between two timestamps. The easiest approach is to handle the rules in a series of if/else if statements:
private String getTimeAsString(int seconds) {
if (seconds < 60) { // rule 1
return String.format("%s seconds ago", seconds);
} else if (seconds < 3600) { // rule 2
return String.format("%s minutes ago", seconds/60);
} // ... and so on
}

Better way to check if a joda.time.Interval spans exactly 1 calendar week (accounting for daylight savings etc)

Is there a better way of doing this?
boolean oneCalendarWeek = interval.getStart().plusWeeks(1).equals( interval.getEnd() );
I guess the following won't work because of the way equals is implemented...
boolean oneCalendarWeek = interval.toPeriod().equals( Weeks.ONE );
From the comments:
i really want to know if the api supports something like my second example which i think is clearer than the first
While the example using Weeks.ONE does not work (since Period.equals() first checks if the two Period instances support the same number of fields, and Weeks.ONE only supports one field), this should work instead:
boolean oneCalendarWeek = interval.toPeriod().equals( Period.weeks(1) );
Here is a code sample that tests this for an interval that starts before the start of DST and ends while in DST. However, I'm not 100% sure how this would behave if the start or end time of the Interval fell exactly on the DST boundary.

Categories

Resources