Date Functions in Android Client for Azure Mobile Service - android

I have an Azure Mobile Service which returns date to an Android Client in this format
"Sat Sep 27 22:48:48 PDT 2014"
I want to calculate the difference between this returned date and today's date. After much iterations here is my current function.
public String calculateDayDifference(String DateFromAzure){
SimpleDateFormat AzureDateFormat = new SimpleDateFormat("EEE MMM dd H:m:s yyyy");
Calendar cal = Calendar.getInstance(Locale.getDefault());
String result;
try {
String currentDate = AzureDateFormat.format(System.currentTimeMillis() * 1000L);
Date presentDate = AzureDateFormat.parse(currentDate);
Date billDueDate = AzureDateFormat.parse(DateFromAzure);
long diff = billDueDate.getTime() - presentDate.getTime();
result = Long.toString(diff);
} catch (ParseException e) {
result = Long.toString(- 1);
//e.printStackTrace();
}
return result;
}
And here is how I call this function from my Adapter's getView() method
viewHolder.txtNumberDays.setText(mDateFunctions.calculateDayDifference(
viewHolder.billSummary.getBillDueDate().toString()))
And here is the Java class field that maps to the date column in the Mobile Service table.
#SerializedName("billDueDate")
private Date BillDueDate;
No matter how I tweak it, it give me negative result like so. How can I re-write the method above to return the difference between today's date and the date returned from Azure Mobile Service table?

Ok, from the AMS Android SDK source code I can see that the SDK handles formatting and parsing of dates automatically so what is returned is a valid java.util.date object.
https://github.com/Azure/azure-mobile-services/blob/master/sdk/android/src/sdk/src/com/microsoft/windowsazure/mobileservices/DateSerializer.java
With this realization I just called getTime() method on the returned date so I can compare it again current date which can be obtained from System.CurrentTimeMillis(). I then converted the result to int and that was with. Long learning experience. Its not the most efficient way to handle this but it works for. Here is the code
mBillDueDateService.mBillTable
.execute(new TableQueryCallback<Bill>() {
#Override
public void onCompleted(List<Bill> result, int count,
Exception exception, ServiceFilterResponse response) {
if (exception == null){
for (Bill bill : result){
long timeInLong = bill.getBillDueDate().getTime();
long currentTime = System.currentTimeMillis();
long diffTime = timeInLong - currentTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
int daysdiff = (int) diffDays;
Log.i(TAG, "Bill Name " + bill.getBillName() + "" + "Due in " + daysdiff + "days");
bill.setDaysBeforeDueDate(daysdiff);
mUpcomingBillAdapter.add(bill);
}

Related

Why my unit test fails altough method works good?

I try to count time interval. I parse String date into Date object for some pattern.
public static float countTimeAgo(String timestamp){
// date pattern
SimpleDateFormat simpleDateFormat
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
simpleDateFormat.setLenient(false);
// time interval
float diff;
try {
// convert timestamp to given pattern
Date timestampDate = simpleDateFormat.parse(timestamp);
// get actual date and convert to pattern
Date date = new Date();
simpleDateFormat.format(date);
// count difference in millis
diff = date.getTime() - timestampDate.getTime();
// convert millis to minutes
diff = diff/(1000*60);
} catch (ParseException e) {
return -1;
}
if (diff < 0)
return -1;
else
return diff;
}
When I put string "2018-03-08 23:28:07.807353" as argument while running my app, method is returning non -1 value. But when I run a test, it fails:
#Test
public void testCountTimeAgo(){
String date = "2018-03-08 23:28:07.807353";
assertTrue(PostTimeProvider.countTimeAgo(date) != -1);
}
AssertionError:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertTrue(Assert.java:52)
Does somebody knows why?
In your code -1 can be returned when the parsing fails or if the date was in future. You should check which one is happening in this case. Perhaps your device and the device running the unit tests have different time?

How can I measure time elapsed since a specific event triggered in my android app?

I have an app where the user gets a task every day so what is the best method to use to keep track of time for a period of a day including any system condition even if the user turned his phone off.
I found a suggestion to use SystemClock.elapsedRealTime() but it doesn't include the phone being turned off ... so any other suggestions ?
Try to save (in SharedPreferences for example) the time of getting the task. Then when you want to get the period from this time to now you can do something like this:
long milliSecondsTriggering -> the milliseconds of the time of triggering the event;
long milliSecondsCurrentTime -> current time in milliseconds;
long periodSeconds = (milliSecondsCurrentTime - milliSecondsTriggering ) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;
try this method once:
call this method by passing long value of your time
public static String getDateDifferenceInDays(long timeInMillis) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
SimpleDateFormat simpleDateFormatParse = new SimpleDateFormat("dd MM yyyy");
Date serverDate = new Date(timeInMillis * 1000L);
Date localDate = new Date();
String strDay = "";
try {
Date dateServer = simpleDateFormatParse.parse(simpleDateFormat.format(serverDate));
Date dateLocal = simpleDateFormatParse.parse(simpleDateFormat.format(localDate));
long diff = dateServer.getTime() - dateLocal.getTime();
//Log.d(TAG, "server date-----" + dateServer + "-----local date----" + dateLocal);
long days = diff / (24 * 60 * 60 * 1000);
//long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
if (days >= 0) {
strDay = "Days left - " + days;
} else {
strDay = "Time elapsed";
}
} catch (ParseException e) {
e.printStackTrace();
}
return strDay;

How to convert number to hour and minute in android

In my application i should show hour and minute and i get this numbers from server with this sample :
Json :
{
data:{
time:84561
}
}
i should get this number from time and show it with this format
**hh : mm : ss**
I can get number of time, but i can't convert this to **hh : mm : ss** .
How can i it?
long timeSec= 84561;// Json output
int hours = (int) timeSec/ 3600;
int temp = (int) timeSec- hours * 3600;
int mins = temp / 60;
temp = temp - mins * 60;
int secs = temp;
String requiredFormat = hours+ ": "+mins+": "+secs;//hh:mm:ss formatted string
Java 9 answer
Duration time = Duration.ofSeconds(87561);
String hms = String.format("%02d : %02d : %02d",
time.toHoursPart(),
time.toMinutesPart(),
time.toSecondsPart());
Unfortunately in Java 8 Duration does not lend itself well to formatting. The methods I use in the snippet are introduced in Java 9 and will calculate the values for hh, mm and ss. Then String.format() does the rest.
I know you cannot use this on Andriod (yet), but I wanted to have this answer stand here for others who can use Java 9, now or in the future.
Very simple
If this is unix time then it will be converted into human readable time format with this snippet.
String relavtiveTimeString = String.valueOf(DateUtils.getRelativeTimeSpanString(unixTime));
You can use new Date(unix); and with below function you can get formatted date. You can format in different style.
//This mehtod convert the date into standard date like : 2017-12-23
public static String getformateDate(Date dateObject) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(dateObject);
}
For more information check this link already answer :
Convert unix time stamp to date in java
Referance:
https://developer.android.com/reference/android/text/format/DateUtils.html
https://developer.android.com/reference/android/text/format/Time.html
Pass your Number or timestamp and convert to milliseconds for hour and minute.use the below code.
public static String getCurrentTimeStamp(String mCurrentTime) {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
TimeZone tz = TimeZone.getDefault();
format.setTimeZone(tz);
// System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
SimpleDateFormat dateParser = new SimpleDateFormat("dd/MM/yyyy hh:mm a z");
Date dateTime = null;
try {
dateTime = dateParser.parse(format.format(Long.parseLong((mCurrentTime)) * 1000));
Log.e("Starttime", "Starttime" + format.format(dateTime));
return format.format(dateTime);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
Try This Logic Use it As per Requirement
public class Test {
public static void main(String[] args) {
String json = "{\n" +
" data:{\n" +
" time:84561\n" +
" }\n" +
"}";
Date date = new Gson().fromJson(json, Date.class);
long milli = date.getTime() * 1000;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println(simpleDateFormat.format(new java.util.Date(milli)));
}
class Date implements Serializable{
int time;
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
}
Output
05:30:00
If you want to download Gson jar download it from
here

Local time to EST time Conversion

Android Local time to EST time Conversion
Code:
SimpleDateFormat serverDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
serverDateFormat.setTimeZone(TimeZone.getTimeZone("EST"));
Calendar calender= Calendar.getInstance(Locale.getDefault());
String time=serverDateFormat.format(calender.getTime());
but i getting wrong time.
one hour difference from right time.
for eg :
local time : Tue Jul 07 17:30:00 GMT+05:30 2015
formated time : 2015/07/07 07:00:00
right time : 2015/07/07 08:00:00
Your problem is using the identifier "EST" which stands for "Eastern Standard Time". As the name suggests it does not use daylight saving rules. Proof:
TimeZone tz = TimeZone.getTimeZone("EST");
long offset = tz.getOffset(System.currentTimeMillis()) / (1000 * 3600);
System.out.println(tz.getID() + ":" + tz.useDaylightTime() + "/" + offset);
// output: EST:false/-5
Use the timezone id "America/New_York" instead:
tz = TimeZone.getTimeZone("America/New_York");
offset = tz.getOffset(System.currentTimeMillis()) / (1000 * 3600);
System.out.println(tz.getID() + ":" + tz.useDaylightTime() + "/" + offset);
// output: America/New_York:true/-4
Then you will observe daylight saving time in July making an offset difference of (+05:30) - (-04:00) = +09:30 resulting in the expected local time 8 AM.
hey please try this function for time conversion -
public static String getTime(String time, SimpleDateFormat sdf) {
String convertedTime = "";
try {
TimeZone timeZone = TimeZone.getDefault();
Date postdate = sdf.parse(time);
long postTimeStamp = postdate.getTime() + timeZone.getRawOffset();
String dateString = sdf.format(new Date(postTimeStamp));
convertedTime = dateString;
// convertedTime = getLastTime(context, time);
} catch (Exception e) {
e.printStackTrace();
}
return convertedTime;
}

How to get the Time like facebook post eg. 1sec ago or 3hrs ago, In android application

I have developed an application where the user receives the message from other application user. I want to just show the time like Facebook, eg. 1sec ago or 3Hrs ago. Something in this fashion. I tried a code from one of our Fellow S.O expert but that code seems to misbehave.
Here's the code which i used in my app.
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
static int[] steps = { 1, 60, 3600, 3600 * 24 };
static String[] names = { "sec", "mins", "hrs", "days" };
public static String formatDelay(String date) {
try {
Date d = sdf.parse(date);
Long stamp = d.getTime();
Calendar c = Calendar.getInstance();
Long now = System.currentTimeMillis() / 1000;
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
String time = format.format(now);
Long dif = now - stamp;
dif = dif / 1000;
if (stamp > now)
return "";
for (int i = 0; i < steps.length; i++) {
if (dif < steps[i]) {
String output = Long.toString(dif / steps[i - 1]) + " "
+ names[i - 1];
return output;
}
}
return Long.toString(dif / steps[3]) + " " + names[3];
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
When I used this code and sent a message from my application , it should show me sent 1sec ago, but in my case it shows me wrong time delay. For eg. I sent the message at 6pm then when I check my application sent item at 6:15pm its should show me 15 mins ago. But it shows me 12 hrs. When i debugged code, got to know that now time show date as 1970 00:00:00, this is because Long now = System.currentTimeMillis() / 1000; when i remove that /1000 it shows me correct date and time. I am clue less why this is happening please help.
Use
android.text.format.DateUtils.getRelativeTimeSpanString (long time, long now, long minResolution, int flags)
this will return time span in String format
For eg. if you pass a long value corresponding to 42 minutes ago in time and flags as DateUtils.FORMAT_ABBREV_RELATIVE the method will return 42 minutes ago
Official documentation DateUtils.getRelativeTimeSpanString
When you divide System.currentTimeMillis() by 1000 you are converting its value to seconds.
You're then using that value to create a date which is interpreting the seconds value as the milliseconds since Thu Jan 01 1970, hence the date difference.
I would recommend using Joda-Time API. See this answer for reference.

Categories

Resources