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)) {
..}
Related
I am trying to add a list of holidays to my calendar. I am using the Caldroid library for displaying the calendar. I want to display a list of holidays in every month for which I need to select specific dates in every month. How do I do that ? The following is what I have tried:
CODE :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -18);
Date blueDate = cal.getTime();
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 16);
int diff = cal.get(Calendar.JANUARY);
cal.add(diff, 10);
Date greenDate = cal.getTime();
I believed that diff would set the month to January and highlight the 11th of January cause I have given the value as 10 but it doesn't do so and I believe it is because I have instantiated the cal to getInstance() which would return the current month.
UPDATE :
Thanks to Meno, I have achieved the following but when I set the calendar to the second time, it takes only the updates value and does not set the first date (very obvious) but I want to know how to set multiple dates in a month without re-instantiating a new GregorianCalendar object for every month. Simply put, how do I set an array of dates in a month.
GregorianCalendar greg_cal = new GregorianCalendar();
greg_cal.set(Calendar.MONTH, Calendar.JANUARY);
greg_cal.set(Calendar.DAY_OF_MONTH, 1);
greg_cal.set(Calendar.MONTH, Calendar.JANUARY);
greg_cal.set(Calendar.DAY_OF_MONTH, 18);
Thanks in advance.
Your question does not appear to be clear. Nevertheless I try an answer. Instead of
cal = Calendar.getInstance(); // In Thailand this gives the buddhist calendar, do you want this?
cal.add(Calendar.DATE, 16); // 16 days from now, what is the intention or meaning???
cal.add(diff, 10); // first argument must be a defined constant in java.util.Calendar
I assume you just want to select a fixed date (as holiday). If so then you can call the set()-method and don't need to add days to move your calendar date forth and back:
GregorianCalendar cal = new GregorianCalendar(); // including currrent year
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 11);
Then you get as date the 11th of January in current year. By the way:
int diff = cal.get(Calendar.JANUARY);
This line is nonsense because:
Calendar.JANUARY is an int constant which is zero and denotes a value (the month) not a field. But the get(int)-method expects a field constant. The field constant with value zero corresponds to Calendar.ERA. Finally the line yields the era of cal, namely int diff = GregorianCalendar.AD = 1; assuming you use the gregorian calendar. This is surely not what you want???
UPDATED because of extra question in comment:
Reusing means that you don't create a new instance for the next calculation but reuse the same one (GregorianCalendar is mutable!). For example:
GregorianCalendar cal = new GregorianCalendar(); // including currrent year
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 11);
Date holiday1 = cal.getTime();
cal.set(Calendar.MONTH, Calendar.DECEMBER); // no new instance => reuse cal
cal.set(Calendar.DAY_OF_MONTH, 24);
Date holiday2 = cal.getTime();
...
I have also written about limiting to manipulations of month and day-of-month only because with manipulation of week-related fields the state of reused Calendar-instance depends on the order of field manipulations (very ugly and surprising).
Anyway, it is always safer to use immutable types which are available in Java 8 (not useable on Android), JodaTime and my alpha-state-library. I admit that the first contact with JodaTime can cause you feeling like lost because there are so many methods (the documentation standard is good for open-source but less good than for example in JSR-310). In your use-case I would use the type org.joda.time.LocalDate as start because you really have just a plain-date-use-case. Google and SO are your friends if you want to see more documentation beyond the original Joda documentation.
UPDATE due to extended question:
You have forgotten one important thing in your new code, namely to add the results of calendar setting to a holiday list, see here the modification:
List<Date> holidays = new ArrayList<Date>();
GregorianCalendar greg_cal = new GregorianCalendar();
greg_cal.set(Calendar.MONTH, Calendar.JANUARY);
greg_cal.set(Calendar.DAY_OF_MONTH, 1);
holidays.add(greg_cal.getTime());
greg_cal.set(Calendar.MONTH, Calendar.JANUARY);
greg_cal.set(Calendar.DAY_OF_MONTH, 18);
holidays.add(greg_cal.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (Date d : holidays) {
System.out.println(sdf.format(d));
}
// output:
2014-01-01
2014-01-18
In an external library like JodaTime you would just use org.joda.time.LocalDate instead.
List<LocalDate> holidays = new ArrayList<LocalDate>();
LocalDate today = LocalDate.now();
holidays.add(today.withMonthOfYear(1).withDayOfMonth(1));
holidays.add(today.withMonthOfYear(1).withDayOfMonth(18));
It is pretty simple (similar in my unfinished date-and-time-library, too).
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()
}
I create a date and then format is like this:
Example 1:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
String currentDate = sdf.format(new Date());
What I would like to do is check if this date is before another date (also formatted the same way). How would I go about doing this?
Example 2:
Also, how would I check whether one of these is before another:
long setForLong = System.currentTimeMillis() + (totalTime*1000);
String display = (String) DateFormat.format("HH:mm:ss dd/MM/yyyy", setForLong);
EDIT:
I think more detail is needed. I create a date in two different ways for two different uses. The first use just formats the current date into a string so it is readable for the user. In the second case, I am using a date in the future with System.currentTimeMillis and adding on a long. Both result in a string.
Both methods format the date in exactly the same way, and I set the strings into a TextView. Later, I need to compare these dates. I do not have the original data/date/etc, only these strings. Becasue they are formatted in the same way, I though it would be easy to compare them.
I have tried the if(String1.compareTo(String2) >0 ) method, but that does not work if the day is changed.
If you only have two String objects that are dates available to you. You will need to process them in something, either in your own comparator class or in another object. In this case, since these are already formatted into dates, you can just create Date objects and compare using the methods previously posted. Something like this:
String string = "05:30:33 15/02/1985";
Date date1 = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.ENGLISH).parse(string);
String string2 = "15:30:33 01/02/1985";
Date date2 = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.ENGLISH).parse(string2);
if(date1.getTime()>date2.getTime()) {
//date1 greater than date2
}
else if(date1.getTime()<date2.getTime()) {
//date1 less than date2
}
else {
//date1 equal to date2
}
You should use Calendar for convenient comparing dates.
Calendar c1 = Calendar.getInstance();
c1.setTime(Date someDate);
Calendar c2 = Calendar.getInstance();
c2.setTime(Date anotherDate);
if(c1.before(c2)){
// do something
}
And you can format it at any time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
String currentDate = sdf.format(c1.getTime());
I am working on an application in which I have to convert a long value to a Date string and display. To achieve the purpose I am using following function, but it is returning me the date from 70's and 80's obviously not appropriate. I am using the following finction:
public static String convertDateFromLongToCompleteString(long date) {
Date d = new Date(date * 1000);
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
String formattedDateFromLong = dateformat.format(d);
return formattedDateFromLong;
}
The long value is just simply System.currentTimeMillis() and when I have to show it to the user, I have to format that for which I am using above function. I have checked system and device dates, their zones and time, everything is just fine. Please update that why is this issue appearing and how can I get the exact date. Thanks!
Edit
I have also tried withoout multiplication with 1000, it gives me time and date from 1970.
If your long date is simply System.currentTimeMillis(), then multiplication with 1000 is not required.
Date d = new Date(date);
Replace Date d = new Date(date * 1000); with Date d = new Date(date);
In case you're using the above method only with System.currentTimeMillis(), you can call Date constructor without any parameters, it will give you the Date object that refers to the current date and time. This will be an easier way to solve your problem. Hope this helps.
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:)