Java - change Minutes and Seconds to time format? (mm:ss) - java

i started with total milliseconds, which I've converted to to total minutes and total seconds:
long minutes = TimeUnit.MILLISECONDS.toMinutes(itemDuration);
long seconds = TimeUnit.MILLISECONDS.toSeconds(itemDuration)
- TimeUnit.MINUTES.toSeconds(minutes);
Now I want to display the minutes and seconds in a mm:ss format (and if occasionally there are hours, then convert to hh:mm:ss format). how would i go about doing this?
thanks!
edit: I've tried using SimpleDateFormat, however it would display the wrong time in time zone that differ by half an hour vs a full hour. (ie: if the time zone was GMT +5:30 and the item duraction was 5 seconds, the app would display 30:05 instead of 00:05).. however it works fine for other time zones that differ by a full hour, such as GMT+5.
unless i'm doing something wrong with the SimpleDateFormat?
private static final SimpleDateFormat mLengthFormatter = new SimpleDateFormat("mm:ss", Locale.getDefault());
(also, just out of curiosity, if I use a SimpleDateFormat, and the number of minutes is greater than 2 digits, then what would happen? would it max out at 99?)

Could probably do it with a string formatter.
formatter.format("%2d:%2d", minutes,seconds);

Related

How to get time difference/duration in hour and minute along with in java?

In my project, I need to find duration of staying outside in office time of an employee from goToVisitTime and returnTime. The main concerning point is goToVisitTime and returnTime both are date (java.util) type [getting from other method, can't change anymore] and styingOutSideTime also must be date (java.util) type. For example:
Date goTOvisitTime = "12:25";
Date returnTime = "14:19";
So, output should be like,
styingOutSideTime = "01:54";
Therefore my method looks like below:
public Date getDiffTime(Date goTOvisitTime, Date returnTime) {
//calculate difference
return styingOutSideTime;
}
I have spent lots of time to determine the solution. I tried to use almost all of Date and Time from Java and Joda Time as well. Additionally, I went through the following links
How to calculate time difference in java?
Java how to calculate time differences
Convert seconds value to hours minutes seconds?
How to get hour/minute difference in java
However, almost all of the solutions are either parameter or return value is a string. additionally, returning either hour or minute only.
First of all, the duration should not be a Date, it should be a java.time.Duration.
If you only want to the hour part and the minute part, you can do it like this:
Duration duration = Duration.between(goTOvisitTime.toInstant(), returnTime.toInstant());
int hours = duration.toHoursPart();
int minutes = duration.toMinutesPart();
String formattedDuration = String.format("%02d:%02d", hours, minutes);

How to parse duration in format "HHmm" using JodaTime?

I'm trying to shift datetime by a Duration which I get in the format "HHmm", for example "0010" meaning 10 minutes.
I've found similar ticket (Parsing time strings like "1h 30min") but I can't make it work properly.
Here's the code:
PeriodFormatter hoursMinutes = new PeriodFormatterBuilder().appendHours().appendMinutes().toFormatter();
Duration duration = hoursMinutes.parsePeriod("0010").toStandardDuration();
duration.getStandardMinutes(); //Returns 600
For some reason, I get 600 minutes instead of 10. So it looks like the minutes were interpreted as hours, but I can't understand why. I've tried adding .maximumParsedDigits(2) for hours, but the result was the same.
Why is my code wrong? Is there some other way to initialize duration parser? Something, where I could just use the standard format like "HHmm"?
So the issue was really with the maximum parseddigits. I only had to add it before hours, not minutes. So the solution is this:
PeriodFormatter hoursMinutes =
new PeriodFormatterBuilder().maximumParsedDigits(2).appendHours().appendMinutes().toFormatter();
Duration duration = hoursMinutes.parsePeriod("0010").toStandardDuration();
duration.getStandardMinutes(); //Returns 10
According to the documentation:
getStandardMinutes
public long getStandardMinutes()
Gets the length of this duration in minutes assuming that there are the standard number of milliseconds in a minute. This method assumes that there are 60 seconds in a minute and 1000 milliseconds in a second. All currently supplied chronologies use this definition.
This returns getMillis() / 60000. The result is an integer division,
thus excess milliseconds are truncated.
Returns: the length of the duration in standard seconds
Seeing as 600 is actually 10 minutes in seconds (60 * 10), you got the answer you expected.

Joda: get local milliseconds of specific timezone

I never would believe that this could amount to being such a hassle. I am trying to make a clock that always displays the local time in specific timezones.
My laptop is currently set in GMT0 timezone (UK).
I want to get the milliseconds of the timezone "Europe/Stockholm".
So let's say it's 17:00 here in the UK I would like to get the milliseconds corresponding to 18:00 which would be the Swedish time.
The time in milliseconds as used by Date is independent of the time zone. Only when you print (or parse) a time, you use a DateFormat that is localized, so it ensures you get the time in the specific timezone.
When time is represented as milliseconds (or seconds or nanoseconds, etc), that is almost always milliseconds since some epoch. In the case of unix and java, this is midnight Jan 1, 1970 UTC.
Time zones are generally arranged as a round number of hours relative to UTC. In certain time zones it's not a round hour but 30 minutes, 15 minutes or 45 minutes from a round hour.
Nevertheless, for any time unit below a minute, all those time zones match UTC exactly.
Therefore, whatever the current second or millisecond is in Sweden, it is the same as it is, for example, in Nepal, whose time zone is 5:45 minutes from UTC.
When you work with an object that allows you to retrieve the separate fields of the given time, the milliseconds field will usually reflect just the number of milliseconds since the beginning of the current second, not the number of milliseconds since midnight. Therefore it will never be more than 999, and it will be the same the world over.
After reading the answers here and discovering another route, this is what finally worked for me.
DateTime curDateTime = new DateTime();
int offset = DateTimeZone.forID("Europe/Stockholm").getOffset(curDateTime.getMillis());
long milli = (curDateTime.getMillis()+offset);

Calculate difference in time (between current and next day)

There is a lot of similar topics but I couldn't find something similar then my problem. I've found only how to calculate if for example second time is greater then first time, like:
22:00
23:00
The result is easy to get. Just subtract second time with first using Date API. Difference is in milliseconds and you can easily convert them in seconds/minutes..
What I want to know, how to get difference between time in first day and time in second day, for example:
22:25
06:30
Difference should be 8 hours and 5 minutes.
Or another example
19:00
00:00
Difference should be 5 hours.
How to calculate time in this way? Any help is appreciated.
Convert your date and time to TimeStamp (It's just the long representation of a date in milliseconds since Jan. 1, 1970.), then calculate difference, and transferred from milliseconds to hours.
Also check this
Use Calendar class. Set your day, hour and minutes and finally subtract those dates (in milliseconds) and you will convert result in hour, minutes and seconds.

Android: Format milliseconds into >60 seconds when no minute format is given

I got a millisecond value. I want to use a format string, to format those milliseconds into a time format. e.g. 45000ms = 45s or 0m 45s or whatever. So this is no special thing. I used SimpleDateFormat for this, but now comes my problem:
61000ms ends up in 1m 1s. This is okay for me, IF there is a minute given in the format string. But when there is no minute given in the format string, it should print out 61s instead of just 1s.
Is there any easy way to achieve this? Currently I dont see it without doing any ugly string formatting code.
I hope you can help me :)
Thanks in advanced!
slain
Edit:
For better understanding:
you got 65400 milliseconds.
format string has minutes, seconds, milliseconds: 1m 5s 400ms
format string has minutes and seconds: 1m 5s
format string has seconds: 65s
format string has seconds and milliseconds: 65s 4ms
format string has minutes and milliseconds: 1m 5400ms
I'm not sure what exactly you are trying to convert but have a look at time units.
If I understand correctly, you are given a number of milliseconds, and a time format string, and need to produce a correctly formatted time? If not, ignore the rest of this...
Maybe not the BEST way, but kind of a nice waterfall: Convert the milliseconds to a set of integers for days, hours, minutes, seconds (or more, or less, depending on the expected range), and then iterate forward through the format string. If day is present, great, stick the number of days in there. If not, skip it, multiply by 24 and add to hours. Do the same for hours->minutes, minutes->seconds, and you should end up with it correctly formatted, even if with weird formats (like days and seconds but not minutes).
Not exactly sure what you're looking for, but you can parse milliseconds like so;
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd MMM yyyy");
public static void main(String[] args) {
final long millis = System.currentTimeMillis();
System.out.println(DATE_FORMAT.format(new Date(millis))); // Prints 05 Aug 2011
}
Obviously, you can tweak the date format as necessary to display seconds, milliseconds, etc.

Categories

Resources