Android getRelativeTimeSpanString not working - android

I am working on notifications and I need to display the time-> An action was performed in a way similar to ("5 seconds ago","12 mins ago","1 week ago" etc.)
This is the code I am using
long now = System.currentTimeMillis();
String datetime1 = "06/12/2015 03:58 PM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date convertedDate = dateFormat.parse(datetime1);
CharSequence relavetime1 = DateUtils.getRelativeTimeSpanString(
convertedDate.getTime(),
now,
DateUtils.SECOND_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
And the result I get is
relativetime1=June 12, 2015
The above obtained result doesn't seem like what its supposed to look like.
By searching online I've found that if that duration is greater than a week, in which case it returns an ABSOLUTE
-I don't quite understand what I found.
How do I achieve my requirement without using an external library?
Kindly help.

Related

JodaTime will always change to 2015 if withYear set to 2016

This is really driving me crazy. The code below
DateTime dt = new DateTime()
.withYear(2014)
.withWeekOfWeekyear(52)
.withDayOfWeek(1);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("d MMM yyyy");
String firstDayOfWeek = dateTimeFormatter.print(dt);
Log.v(FILE_NAME,"display date? " + firstDayOfWeek);
dt = new DateTime()
.withYear(2015)
.withWeekOfWeekyear(52)
.withDayOfWeek(1);
String lastDayOfWeek = dateTimeFormatter.print(dt);
Log.v(FILE_NAME,"display date? " + lastDayOfWeek);
dt = new DateTime()
.withYear(2016)
.withWeekOfWeekyear(52)
.withDayOfWeek(1);
lastDayOfWeek = dateTimeFormatter.print(dt);
Log.v(FILE_NAME,"display date? " + lastDayOfWeek);
Somehow will always output:
display date? 22 Dec 2014
display date? 21 Dec 2015
display date? 21 Dec 2015
As you can see, the last display date should display 2016, not 2015. It seems that everytime I set withYear to 2016, it will magically change to 2015. Is this a bug or am I doing something wrong? I have cleaned and rebuild my project many times but the output is the same.
The method withYear(...) does not do what you think because it uses the standard calendar year and not the year of week date as described in ISO-8601-paper. Please compare following two snippets. Only the second one does what you need:
DateTime dt = new DateTime().withYear(2016).withWeekOfWeekyear(52).withDayOfWeek(1);
System.out.println("joda=" + dt); // joda=2015-12-21T18:26:12.776+01:00
DateTime dt2 =
new DateTime().withWeekyear(2016).withWeekOfWeekyear(52).withDayOfWeek(1);
System.out.println("joda=" + dt2); // joda=2016-12-26T18:27:59.606+01:00
See also the documentation. The fine difference between calendar year and weekbased year is only noticeable at the end or start of a year (like today).
Explained in detail the behaviour:
If choosing new DateTime() for today, the second of January 2017 and then setting the calendar year to 2016 results in: 2016-01-02. But this date is in week-of-year 53 belonging to week-based-year 2015. This 53rd week starts on 2015-12-28, so the expression withWeekOfWeekyear(52) will go back one week to 2015-12-21 (what you observe in first case).

Generate TimeStamp In Android Application Project

I am working on a project that requires the actions of a user to be time logged and represented as for example : 1 min ago, ...3hrs ago...5 days ago. I am new to this and don't know how to proceed. Keep in mind the project is NOT REST based. How do I implement this?
Get time in milliseconds for user action, save that time somewhere and then every time take difference of that time with current time to find out how long this action happens
you can get time in millisecond using
Calendar calendar = Calendar.getInstance();
calendar.getTimeInMillis();
You can get the actual timestamp with:
long timestamp = System.currentTimeMillis();
Regarding your question you can do something like:
long eventTimestamp = System.currentTimeMillis();
..
// some other stuff happens
..
//get the passed time
long actualTimestamp = System.currentTimeMillis();
long timestampDifference = actualTimestamp - eventTimestamp;
int passedSeconds = timestampDifference / 1000; //get the passed time in seconds
int passedMinutes= passedSeconds / 60; //get the passed time in minutes
Since you are on Android you could try the helper class DateUtils built into Android platform. Something similar to this untested code:
String relativeTime =
DateUtils.getRelativeTimeSpanString(
jud.getTime(),
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
If you don't like the API-style or don't find enough features or see other problems like missing timezone awareness then you can also download and try one of two external libraries:
PrettyTime (slim classic library for relative times)
// your possible input
Date jud = new Date(System.currentTimeMillis() - 3600000);
org.ocpsoft.prettytime.PrettyTime pt =
new org.ocpsoft.prettytime.PrettyTime(Locale.ENGLISH);
String relativeTime = pt.format(jud);
System.out.println(relativeTime); // output: 1 hour ago
or my library Time4A (bigger but also more features and languages):
// your possible input
Date jud = new Date(System.currentTimeMillis() - 3600000);
Moment moment = TemporalType.JAVA_UTIL_DATE.translate(jud);
String relativeTime =
net.time4j.PrettyTime.of(Locale.US)
.withShortStyle()
.printRelativeInStdTimezone(moment);
System.out.println(relativeTime); // output: 1 hr. ago
Other libraries don't support printing of relative times well, if at all.

How to get global date and time in android?

In my application some functionality get closed after 9:00 PM. Its working fine if date setting of device is auto updated. But suppose right now its 10:00 pm and user changed the time 10:00 Pm to 08:00 Pm then my code is working. I want to avoid that thing.
Get the system time in UTC (Universal Coordinate Time). This answer gives it in more detail
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
Calendar cal = df.getCalendar();
int hour = cal.get(Calendar.HOUR_OF_DAY);
if (hour > 21 && hour < 9) // or 9:00pm in your time-zone converted to gmt...
{
// Do something, or don't do something
}
you have to use the external time service like this one. anything else like System.currentTimeMillis() or new Date() can be "hacked" by user

Time displayed is different from my system time

I have logged the time taken to post and get a reponse from a server. But the time seems to be 4 hours ahead of my system clock.
The code I used is :
String posttime = java.text.DateFormat.getTimeInstance().format(Calendar.getInstance().getTime());
Log.i("Time at which HTTP POST was sent",""+posttime );
The output in the log is :
Time at which HTTP POST was sent(323): 8:24:53 PM instead of 4:24:54PM.
Any input would be appreciated.
The time is in UTC, you need to change the TimeZone to your local timezone
for example:
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println(sdf.format(calendar.getTime()));

Android Dev: Current Time range check

I'm working on an android application, as part of me trying to learn android programming, that will switch audio profiles based on day and time (provided by the user)... So far I have got most of the layout done, I have also created a service that will run in the background to perform few checks...
Right now I'm having a hard time trying to find an elegant way to handle checking if current time falls in time range saved by the user... I'm saving the user's preference for time range in a string format from androids TimerPicker control, I need to check if the current time falls in the user saved times...
Right now I have the following code:
the 'from time' is coming in with the following: hour:minute:AM/PM -- 8:59:AM in string format
the 'to time' is coming in with the following: hour:minute:AM/PM -- 4:59:PM in string format
if(fromAMPM.equals("AM")){
from.set(from.AM_PM, from.AM);
} else {
from.set(from.AM_PM, from.PM);
}
//dont care about the YEAR and MONTH, so set it to current MONTH and YEAR
from.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, fromHour, fromMinute);
if(toAMPM.equals("AM")){
to.set(to.AM_PM, to.AM);
}else{
to.set(to.AM_PM, to.PM);
}
//dont care about the YEAR and MONTH, so set it to current MONTH and YEAR
to.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, toHour, toMinute);
//this is just for me to see what got set:
SimpleDateFormat df3 = new SimpleDateFormat("HH:mm aaa");
String formattedDate1 = df3.format(from.getTime());
String formattedDate2 = df3.format(to.getTime());
After all this processing:
formattedDate1 is returning: 08:59 AM
formattedDate2 is returning: 04:59 AM
Any suggestions?
Thanks
Take a look at the Calendar documentation, under the section "Inconsistent Information"
http://developer.android.com/reference/java/util/Calendar.html
You call:
to.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, toHour, toMinute);
Which sends toHour as HOUR_OF_DAY (24h), not HOUR (12h).
It says that when you supply it with inconsistent information, it just uses the latest information. You're telling it that toHour is 4 on a 24hour scale, which is inconsistent with your PM setting, so it throws the PM setting away.
The easiest change would probably be just to add 12 to toHour instead of setting the AM_PM. Or, don't use the set(year, month, day, hourofday, minute) command and just set hour and am_pm separately.

Categories

Resources