Android: Comparing getDat() with current Date - android

I have this CalendarView below
and if i click that day which is the Date today it will popup a dialog.. but this Calendar wont popup if u clicked a date before the CurrentDate it will just say u can't add event before the current day/time.. and is running well if i click any day after the date today, but when i click the date today i will say a message just like when i click the date before it...
Here is my Code for comparing dates
long currentTime;
Date curr = new Date();
currentTime = curr.getTime();
if(cw.getDate() >= currentTime || formatDate(cw.getDate()) == formatDate(currentTime))
{
Dialog d = new Dialog(ScheduleActivity.this);
//some code for setting up the dialog
d.show();
}
else
{
Toast toast = Toast.makeText(ScheduleActivity.this, Long.toString(cw.getDate())+" || "+Long.toString(currentTime),10000);
toast.show();
Log.d("timecheck", formatDate(cw.getDate())+" || "+ formatDate(currentTime));
}
I just used that formatDate with a Format of MM/dd/yyyy just to compare the two dates cuz comparing the time stamp alone still does not work (using ">=" )
Btw the toast are changed so i can see what values are being compared... in Milliseconds they are defferent really but when i format it to MM/dd/yy supposed to be it will see it as the same... but it wont go through the if part it'll go to the else part.. i Logged the formattedDate in the logcat, logcat below..
Logcat Logs

You will need to use equals instead of == to compare the strings returned from formatDate:
if(cw.getDate() >= currentTime || formatDate(cw.getDate()).equals(formatDate(currentTime)))

Your pop up is not appearing as you are comparing all the inputs with the current date try with entering other values for comparision by adding previous dates and try it out again it will work:)

Related

How to compare if the new date is after the old date in android

I'm trying to see how I can compare if the new date is after the old date if so no data will be shown from the firebase database. I am having trouble with this because my app crashes when I test it I believe I'm doing something wrong. Can someone help me with this issues? Below is my code. Thanks in advance
//Code
if(dataSnapshot.exists()){
//progressBar.setVisibility(View.GONE);
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
UserInformation2 upload=postsnapshot.getValue(UserInformation2.class);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M-dd-yyyy");
//String now = simpleDateFormat.format(new Date());
Date d=new Date();
String AdCreationDate = postsnapshot.child("created").getValue(String.class);
//SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd")
try {
Date new_date = simpleDateFormat.parse(String.valueOf(d));
Date old_date = simpleDateFormat.parse(AdCreationDate);
if(new_date.after(old_date)){
// Your time expired do your logic here.
Toast.makeText(getContext(), "Your data expired", Toast.LENGTH_SHORT).show();
}else{
myUploads.add(upload);
recyclerView.invalidate();
}
} catch (ParseException e) {
e.printStackTrace();
}
//simpleDateFormat.format(d);
//Date e=new Date(old);
}
linearLayoutWithoutItems.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
Stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.tout, PID: 22667
java.lang.IllegalArgumentException
at java.util.Date.parse(Date.java:638)
Your error isn't in the comparison, it's in the String old = simpleDateFormat.format(new Date(Date.parse(AdCreationDate)));
Check the value of AdCreationDate it might not be compatible with a list of valid date formats that can be parsed, at the very least you can place AdCreationDate into a SimpleDateFormat and then parse that.
You need to change this logic. When working with dates it's always better to work with timestamp. This is easy to convert to date or anything else and also easy to compare between dates.
So, when you are saving your date to the database just save it as
long timestamp = date.getTime(); //this will return time in milliseconds
Then when you retreive the values from database, you don't even have to format them before checking which one is older. You can simply use this:
long database_timestamp = postsnapshot.child("created").getValue();
long current_timestamp = System.currentTimeMillis();
if (current_timestamp > database_timestamp) //this will check if current_timestamp has greater value then database_timestamp, if it has it means that it's date from later in time
Now you can simply convert that to date and use SimpleDateFormat to format it as you want:
Date new_date = new Date(current_timestamp);
SimpleDateFormat format = new SimpleDateFormaT("MM-dd-yyyy");
This also covers each hour, second, minut,e or anything else you need. So, this will also check if the current date is greater than the other one even if there is only a few seconds difference between them. Which means your data will be live. If you don't need this you can also avoid it by setting the hour, minutes, and seconds on the Date to 0.
It looks like the error is actually related to
Date new_date = simpleDateFormat.parse(String.valueOf(d));
If you comment out that line and then update the if statement to
if(d.after(old_date)){
You don't need to parse the new date as it's already a Date object. You only need to parse the date from your snapshot as it is a string.
I'd also change the new date variable d to something more meaningful as it well help the readability of the code and the Java standard for naming variables is to use camel case where the scond word is capitalised without an underscore i.e. 'oldDate'. It's good to get into the habit of following these conventions.

Add one day to calendar to make test if-else

I use DateTime values in my app. I can create Lessons, and I have to set the beginning nd the end of that lesson.
Let's say I create like this :
English - Beginning 07.05.2017 End 07.07.2017
Then I want to modify the end of that lesson and put :
07.06.2017
I check to see if the dates are OK, but I'm not sure about what I did, because I dont want to let the user to modifiy or create lessons in the past, but if he creates a lesson that finishes the current day, that's ok.
I wrote like this in my if else :
String date1 = datedebut.getText().toString();
String date2 = datefin.getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date_debutnew = dateFormat.parse(date_initial);
Date date_derniernew = dateFormat.parse(date_derniercours);
Calendar calendar = Calendar.getInstance();
if (date_debutnew.after(date_derniernew) || date_derniernew.before(calendar.getTime()))
{ ... }
How can I add one day to that calendar ?
Thank you for the future hlep.
You can use compareTo() method of Date.
It will return,
a value 0 if the argument Date is equal to this Date;
a value less than 0 if this Date is before the Date argument;
a value greater than 0 if this Date is after the Date argument.
From what I understand of the problem, your new Finish date should be after the new Start date and before the designated end Date.
so, the condition should be :
if (date_derniernew.after(date_debutnew) || date_derniernew.before(date2)) {
..}

Android - Setting date to RelevantDate with an CursorAdapter

Let me just give an example of the requirements I am trying to fulfill. (Sorry if it's kind of a dumb question but my brain is a little fried right now and I'm working on this by myself)
I have a CursorAdapter (w/ SQLite on the backend) that I am using for my ListView to display content. One of the fields in the list item that I am displaying is the date the item was added to the Listview. So...
CASE:
If today was December 31st, 2013 and I just created a list item I would like it to display "Today". On January 1st, 2014 I would like the date to change to "Yesterday". And finally, on January 2nd, 2014 I would like the date to change to "12/31/2013".
What is the simple or most elegant way of fulfilling these requirements? I don't want to be constantly checking my whole listview for dates and be mean to the CPU. Any ideas on the best practice of saving the date would also be much appreciated!
Thanks!
I think I've got it working... I use this method in the activity where my listview is and call it every onCreate, onStart, and onResume.
public void setRelevantDate() {
SimpleDateFormat year = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Date date = new Date();
String current_date = year.format(date);
String db_day_after_creation_date;
//check dates created, sub "today" or "yesterday"
for(SoundData s: app.unsent_recordings){
Log.e("soundData date flag",String.valueOf(s.isAfter_Day_two()));
Log.e("soundData date buffer",s.getDate_buffer());
Log.e("soundData date created",s.getDate_created());
if (!s.isAfter_Day_two()){ //if we are two days after the creation then we can skip all the checks for this item because
// it has already been set back to the initial MM/dd/yyyy date format
String sql_date = s.getDate_buffer();
String db_date = sql_date.substring(0,10);
String db_time = sql_date.substring(11);
//find the day after creation date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(db_date));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, 1);
db_day_after_creation_date = sdf.format(c.getTime());
if (db_date.equals(current_date)){
s.setDate_created("Today, "+db_time);
app.update_Recording_DateCreated(s.getId(),"Today, "+db_time, s.getDate_buffer(), String.valueOf(s.isAfter_Day_two())); //dateCreated = today, TIME
}
else if(current_date.equals(db_day_after_creation_date)){ // basically if the current date is equal to the day after the db_created date
s.setDate_created("Yesterday, "+db_time);
//we can say that it was created yesterday
app.update_Recording_DateCreated(s.getId(),"Yesterday, "+db_time, s.getDate_buffer(), String.valueOf(s.isAfter_Day_two()));
}
else{
s.setDate_created(sql_date);
//Otherwise use normal date
app.update_Recording_DateCreated(s.getId(),sql_date,s.getDate_buffer(), String.valueOf(s.isAfter_Day_two())); //dateCreated = dateBuffer
}
app.mCursor = app.db.getCursor();
app.rec_adapter.changeCursor(app.mCursor);
app.rec_adapter.notifyDataSetChanged(); //Update cursor, notifyDataSetChanged()
}

How to compare two timestamps in android?

I want to compare two timestamps and if the difference of that is (-+5minuts) then I want to display alert dialog.
i.e. If currently in our watch 4PM the second time is 4.05PM or 3.55PM then alert will display else not.
Can anyone suggest me the way how can I get the solution of this.??
I found after search the function of getting timeStamp and how to compare two timestamps but for this type of condition is there any method or function?
Thanks.
My code is:-
date= new Date();
currentTime = date.getTime();
if(currentTime !=0 && previousTime !=0){
String result = (String) DateUtils.getRelativeTimeSpanString(currentTime, previousTime, 0);
}
And I am storeing current time in to previous time lilke tis way :-
if(currentTime != previousTime){
previousTime = currentTime;
}
There's two approaches you could take, depending on whether you just want to measure time elapsed, or want to set future times to compare to.
The first is similar to Sourabh Saldi's answer, record the result from
long prevEventTime = System.currentTimeMillis();
then compare it with System.currentTimeMillis() until the difference is more than 300000
As you have mentioned, your timestamp from the server is in milliseconds since January the 1st, 1970. This means it is directly comparable to System.currentTimeMillis(). As such, use:
long serverTimeStamp=//whatever your server timestamp is, however you are getting it.
//You may have to use Long.parseLong(serverTimestampString) to convert it from a string
//3000(millliseconds in a second)*60(seconds in a minute)*5(number of minutes)=300000
if (Math.abs(serverTimeStamp-System.currentTimeMillis())>300000){
//server timestamp is within 5 minutes of current system time
} else {
//server is not within 5 minutes of current system time
}
The other method looks closer to what you're already doing - using the Date class to store the current and compared time. To use these, you'll want to be using the GregorianCalendar class to handle them. Calling
calendar=new GregorianCalendar();
will create a new calendar, and automatically set it's date to the current system time. You can also use all the functions supplied in the GregorianCalendar class to roll the time forward or backward using something of the form
calendar.add(GregorianCalendar.MINUTE, 5);
or set it to a Date object's time with
calendar.setTime(date);
In your case, depending on how much flexibility you want both the GregorianCalendar class and the Date class have after() methods, so you probably want something like the following:
Create somewhere:
Date currentDate=newDate();
Then set your alarm point:
calendar=new GregorianCalendar(); //this initialises to the current system time
calendar.setTimeInMillis(<server timestamp>); //change to whatever the long timestamp value from your server is
calendar.add(GregorianCalendar.MINUTE, 5); //set a time 5 minutes after the timestamp
Date beforeThisDate = calendar.getTime();
calendar.add(GregorianCalendar.MINUTE, -10); //set a time 5 minutes before the timestamp
Date afterThisDate = calendar.getTime();
Then check if the current time is past the set alarm point with
currentDate.setTime(System.currentTimeMillis());
if ((currentDate.before(beforeThisDate))&&(currentDate.after(afterThisDate))){
//do stuff, current time is within the two dates (5 mins either side of the server timestamp)
} else {
//current time is not within the two dates
}
This approach can seem a bit more long winded, but you'll find it is very robust and flexible, and can easily be extended to set alarm points far in the future, or use the GregorianCalendar methods to easily set dates hours, days or weeks into the future.
How about just:
private static final long FIVE_MINUTES = 1000 * 60 * 5; //5 minutes in milliseconds
long currentTime = new Date().getTime();
long previousTime = mPreviousTime;
long differ = (currentTime - previousTime);
if (differ < FIVE_MINUTES && differ > -FIVE_MINUTES ){
// under +/-5 minutes, do the work
}else{
// over 5 minutes
}
long etime = 0;
final long time1 = uptimeMillis();
/* do something */
final long time2 = uptimeMillis();
if (time2 < time1) {
etime = Long.MAX_VALUE - time1 + time2;
} else {
etime = time2 - time1;
}
then check this etime and do as required!!1
Use this following method to change your dates in epoch format
public Long getChnagedDate(Activity act,String date) throws ParseException
{
long epoch = new java.text.SimpleDateFormat ("MM/dd/yyyy HH:mm:ss aa").parse(date).getTime();
return epoch/1000;
}
and after check the difference in http://www.epochconverter.com.
Hope it helps you.
Joda time will help you with this task.
import org.joda.time.Interval;
http://joda-time.sourceforge.net/

Compare dates in Android App

I am quite new to Android development, but the person has written the code is away and i have taken over this job.
There is one thing I would like to find out quickly...(--
The app is picking up the user input of a date (using a date picker) and i need add a validation to check the if the date is valid. The valid dates are 30 days from today.
After searching on the internet for long time, i've found a code i might can use:
Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse(today);
if(today.before(predefined)) {
...
}
But I am not sure how to add 30 days?
If you could tell me, that would be much appreciated.
Thanks in advance.
Edit Here is the Source code I've tried.
Calendar today = Calendar.getInstance();
today.add(Calendar.DAY_OF_MONTH,30);
if(calStartDate.compareTo(today)<0) {
Toast.makeText(GetClient.this,"It's before valid date!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(GetClient.this,"It's a valid date!",Toast.LENGTH_SHORT).show();
}
You want the Calendar class. You can create one and set it to current time/date, and create another and set roll it forward 30 days. Then call compareTo() on one passing in the other.
Implement this logic in ur OnDateSetListener:::
class DateListner implements OnDateSetListener
{
#Override
public void onDateSet ( DatePicker view , int year , int monthOfYear ,
int dayOfMonth )
{
Date inputDate = new Date(year, monthOfYear, dayOfMonth);
Long inputTime = inputDate.getTime();
Calendar calendar=Calendar.getInstance();
Date validDate = new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), (calendar.get(Calendar.DAY_OF_MONTH)+30));
Long validTime = validDate.getTime();
if(validTime>inputTime){
Log.e("result", "valid");
}
else
Log.e("result", "invalid");
}
}
Cheers......!!!!

Categories

Resources