I have my server returning a time ago string format like this 2 minutes ago which is fine but I now need to convert it to seconds. I thought of just splitting the string using a space delimiter and getting the first text but then, there are cases of my server returning instances of 5 hour 43 minutes ago etc. My question is this, Is there a neat way of conversion from this time ago format bearing in mind of these instances to just seconds?
I dont think there is a particular library or method that can do the conversion from your "time ago" to seconds. The best option for you would be to parse the "Time ago" string returns by your server and do the conversion yourself. The simplest way would be to split your string on space boundaries then get the values of hours and min.
public static int timeAgoToSeconds(String timeAgo) {
int timeInSec = 0;
String []myStringArray = timeAgo.trim().split(" ");
if(myStringArray.length==3){
timeInSec = Integer.valueOf(myStringArray[0]) *60;
}
if(myStringArray.length==5){
timeInSec = Integer.valueOf(myStringArray[0]) *3600 + Integer.valueOf(myStringArray[2]) * 60;
}
return timeInSec;
}
test in the main() method:
String timeAgoHHmm = "5 hour 43 minutes ago";
String timeAgoMM = "2 minutes ago";
System.out.println(timeAgoToSeconds(timeAgoHHmm));//20580
System.out.println(timeAgoToSeconds(timeAgoMM));//120
Related
This question already has answers here:
How to calculate "time ago" in Java?
(33 answers)
Closed 7 years ago.
I want to display how long ago something happened. For example
24 minutes ago //discard seconds
3 hours ago //discard minutes
5 days ago // discard hours
3 weeks ago // discard days
All I have is a long timestamp and so I am free to use java.util.Date or jodatime or whatever other Time android uses. I am having such a hard time getting it right. I try to use jodatime with minus but I can't quite get the right answer yet.
One approach is for me to do the whole thing myself: first subtract my timestamp from now and then do some arithmetics. But I would rather avoid that route if possible.
Android provides the utility class DateUtils for all such requirements. If I've understood your requirement correctly, you need to use the DateUtils#getRelativeTimeSpanString() utility method.
From the docs for
CharSequence getRelativeTimeSpanString (long time, long now, long minResolution)
Returns a string describing 'time' as a time relative to 'now'. Time spans in the past are formatted like "42 minutes ago". Time spans in the future are formatted like "In 42 minutes".
You'll be passing your timestamp as time and System.currentTimeMillis() as now. The minResolution specifies the minimum timespan to report.
For example, a time 3 seconds in the past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS
You can use the following code :
public class TimeAgo {
public static final List<Long> times = Arrays.asList(
TimeUnit.DAYS.toMillis(365),
TimeUnit.DAYS.toMillis(30),
TimeUnit.DAYS.toMillis(1),
TimeUnit.HOURS.toMillis(1),
TimeUnit.MINUTES.toMillis(1),
TimeUnit.SECONDS.toMillis(1) );
public static final List<String> timesString = Arrays.asList("year","month","day","hour","minute","second");
public static String toDuration(long duration) {
StringBuffer res = new StringBuffer();
for(int i=0;i< Lists.times.size(); i++) {
Long current = Lists.times.get(i);
long temp = duration/current;
if(temp>0) {
res.append(temp).append(" ").append( Lists.timesString.get(i) ).append(temp > 1 ? "s" : "").append(" ago");
break;
}
}
if("".equals(res.toString()))
return "0 second ago";
else
return res.toString();
}
}
Just call the toDuration() method with your long timestamp as parameter.
You can also use DateUtils.getRelativeTimeSpanString() . You can read the documentation here Date Utils
This question already has an answer here:
How to calculate difference between two dates in years...etc with Joda-Time
(1 answer)
Closed 8 years ago.
I have a long-variable which represents an amount of delay in milliseconds. I want to transform this long to some kind of Date where it says how many hours, minutes, seconds, days, months, years have passed.
When using Date toString() from Java, as in new Date(5).toString, it says 5 milliseconds have passed from 1970. I need it to say 5 milliseconds have passed, and 0 minutes, hours, ..., years.
you cannot get direct values , without any reference date for your requirements, you need define first reference value like below:
String dateStart = "01/14/2012 09:29:58";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
Date d1 = format.parse(dateStart);
the above is your reference date , now you need to find the current date and time using following.
long currentDateTime = System.currentTimeMillis();
Date currentDate = new Date(currentDateTime);
Date d2.format(currentDate)
and the difference of these values like long diff=d2-d1 will gives values in milliseconds.
then
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
and similarly for months and years.
you can also refer the example given on this link for more information http://javarevisited.blogspot.in/2012/12/how-to-convert-millisecond-to-date-in-java-example.html
From what I understand from your question you could achieve your goal by writing a method that will suit your needs i.e.:
static public String dateFromMili (long miliseconds) {
// constants that will hold the number of miliseconds
// in a given time unit (year, month etc.)
final int YEAR_IN_MILISECONDS = 12*30*24*60*60*1000;
final int MONTH_IN_MILISECONDS = 30*24*60*60*1000;
final int DAY_IN_MILISECONDS = 24*60*60*1000;
final int HOUR_IN_MILISECONDS = 60*60*1000;
final int MINUTE_IN_MILISECONDS = 60*1000;
final int SECONDS_IN_MILISECONDS = 1000;
// now use those constants to return an appropriate string.
return miliseconds +" miliseconds, "
+miliseconds/SECONDS_IN_MILISECONDS+" seconds, "
+miliseconds/MINUTE_IN_MILISECONDS+" minutes, "
+miliseconds/HOUR_IN_MILISECONDS+" hours, "
+miliseconds/DAY_IN_MILISECONDS+" days, "
+miliseconds/MONTH_IN_MILISECONDS+" months, "
+miliseconds/YEAR_IN_MILISECONDS+" years have passed";
}
Than you will have to pas the number of miliseconds as a parameter to your new function that will return the desired String (i.e for two seconds):
dateFromMili (2000);
You could also print your answer:
System.out.println(dateFromMili(2000));
The result would look like this:
2000 miliseconds, 2 seconds, 0 minutes, 0 hours, 0 days, 0 months, 0 years have passed
Note that this method will return Strings with integer value (you will not get for example "2.222333 years" but "2 years"). Furthermore, it could be perfected by changing the noun from plural to singular, when the context is appropriate ("months" to "month").
I hope my answer helped.
This is how I solved the problem:
I used a library called Joda-Time (http://www.joda.org/joda-time/) (credits to Keppil!)
Joda-Time has various data-structures for Date and Time. You can represent a date and time by a DateTime-object.
To represent the delay I was looking for, I had two options: a Period data-structure or a Duration data-structure. A good explanation of the difference between those two can be found here: Joda-Time: what's the difference between Period, Interval and Duration? .
I thus used a Duration-object, based on the current date of my DateTime-object. It has all the methods to convert the amount of milliseconds to years, months, weeks, days, hours, minutes and seconds.
I am trying to take have a time that counts down all the way to 0 from 1 minute.
I have already created my timer. I just need to know how do i convert a int such as 100 to a String to show 1:00 as in a minute and keep counting down like minus 1 secodn from the int and convert it to the String :59?
Any suggestions?
If I understand your question correctly you simply want to divide your number by 60 to get the minutes and then mod your number by 60 to get the seconds and then concat the strings.
int remainingTime = 100;// or whatever number of seconds you have left
String min = (remainingTime / 60) + "";
String sec = (remainingTime % 60) + "";
String remainingTimeStamp = "min" + ":" + "sec";
If you want to get fancy with it, check to see if min and sec are less than 10 and append a leading zero, so that it looks like 01:05 rather than 1:5
I'm not sure what you mean by "I already have my timer". I'll wait for you to update your question, rather than speculate as to what you might mean, before I continue elaborating.
To add to this, check the http://developer.android.com/reference/android/text/format/DateUtils.html class. Note that this is not in 'org.apache' which has another DateUtils class.
Edit:
Since it appears you were looking for formatting 100 seconds here is it formatted:
SimpleDateFormat df = new SimpleDateFormat("mm:ss");
String formatted = df.format(remainingTime * 1000);
i trying to convert time in string format to minutes. i can use substring and find the minutes but there is a problem because there is a chance of getting time in the format 720:00 hours. (as i am calculating time for many days) pls help with me....
Thanks in advance........
Hussain
As far as I understood, you need to calculate how many minutes are in the given hours and minutes. Well, I'd do it fast and simple:
String time = "725:00";
String[] parts = time.split(":",2);
int hours = Integer.valueOf(parts[0]);
int minutes = Integer.valueOf(parts[1]);
return hours*60+minutes;
With Groovy, you could do something like this:
def time = '720:00'
def minutes = time.split(':').with {
(h,m) = it as int[]
h * 60 + m
}
In Java use String.split(":") and take the second element of the array.
Assuming that the time is in "hour:minute" format.
Currently I have a function which can take the start time and end time of one day, and calculate the difference between the two, giving me the hours worked in a day. What I would like to do is be able to get the hours worked for 7 days, and return a grand total, while remaining with the display format (HH:mm).
My function for a single day's total:
Period p = new Period(this.startTime[dayIndex], this.endTime[dayIndex]);
long hours = p.getHours();
long minutes = p.getMinutes();
String format = String.format("%%0%dd", 2);//Ensures that the minutes will always display as two digits.
return Long.toString(hours)+":"+String.format(format, minutes);
this.startTime[] & this.endTime[] are both arrays of DateTime objects.
Any suggestions?
You'll need something to hold a week's worth of days, and call your function once for each day.
But that means you'll want to refactor so that your calculator method doesn't format as a string, but instead returns a numeric value, so you can easily add them together.
Another simple solution:
Here is a method that receives separate the hours and minutes.The parameters are:
Start Hour
Start Minutes
End Hour
End Minutes
first, calculate the difference between hours and minutes separate:
int hours = pEndHour - pStartHour;
int minutes = ((60 - pStartMinutes) + pEndMinutes) - 60;
then, validates if the value of "minutes" variable is negative:
// If so, the "negative" value of minutes is our remnant to the next hour
if (minutes < 0) {
hours--;
minutes = 60 + minutes ;
}
Finally you can print the period of time in the hour format:
String format = String.format("%%0%dd", 2);
System.out.println( "*** " + hours + " : " + minutes);
That's all.
Solution I ended with for those interested
Period[] p=new Period[7];
long hours = 0;
long minutes =0;
for(int x=0; x<=this.daysEntered;x++)
{
p[x] = new Period(this.startTime[x], this.endTime[x]);
hours += p[x].getHours();
minutes += p[x].getMinutes();
}
hours += minutes/60;
minutes=minutes%60;
String format = String.format("%%0%dd", 2);
return Long.toString(hours)+":"+String.format(format, minutes);