working with datetime to check which one is bigger - java

I have two datetime values and i dont knw how to compare them. I know if i had only date values then before() and after() methods would have worked but i have no idea about Datetime values. All i have done is below plz tell me if its correct ?? and plz do guide me if its not a good way and a better alternative is available.
Date now = new Date();
DateTime currenttime = new DateTime(now, TimeZone.getTimeZone("IST"));
DateTime edate = e.getEnd().getDateTime();
if(currenttime.getValue()>edate.getValue())
{
//here I want to do the logic to delete this event.
}
e refers to the event object that is of google calendar. All i want to do here is check if Event e is past todays date and time. and if it is then i wanna delete the event.

You can use jdk Calendar to get and check days:
public boolean isDatePass(Date date) {
Calendar calendar = Calendar.getInstance();
// Getting day of year and year of checked date:
calendar.setTime(date);
int checkedYear = calendar.get(Calendar.YEAR);
int checkedDay = calendar.get(Calendar.DAY_OF_YEAR);
// Getting day of year and year of current date:
calendar.setTime(new Date());
int currentYear = calendar.get(Calendar.YEAR);
int currentDay = calendar.get(Calendar.DAY_OF_YEAR);
if(checkedYear != currentYear) {
return checkedYear < currentYear;
}
return checkedDay < currentDay;
}
For yoda DateTime:
public boolean isDatePass(DateTime date) {
// Getting day of year and year of checked date:
int checkedYear = date.getYear();
int checkedDay = date.getDayOfYear();
// Getting day of year and year of current date:
DateTime currentTime = new DateTime(now, TimeZone.getTimeZone("IST"));
int currentYear = currentTime.getYear();
int currentDay = currentTime.getDayOfYear();
if(checkedYear != currentYear) {
return checkedYear < currentYear;
}
return checkedDay < currentDay;
}
Not days only but time:
public boolean isDatePass(DateTime date) {
DateTime currentTime = new DateTime(now, TimeZone.getTimeZone("IST"));
return date.isAfter(currentTime);
}
More simple solution (according to javadoc when pass null to isAfter/isBefore this mean current or now):
public boolean isDatePass(DateTime date) {
return date.isAfter(null); // but it does not take in account time zone
}

public String deleteEvents() throws ParseException {
try {
boolean evtDelMsg = false;
int iEvtCnt = 0;
int totalEvents = lstEvents.size();
System.out.println("events are :"+lstEvents.getItems().toString());
if(lstEvents.size()>0)
{
for(Event e : lstEvents.getItems())
{
System.out.println("startdate is "+e.getStart().toString());
Date now = new Date();
try
{
if((new Date()).getTime() < e.getEnd().getDateTime().getValue())
{
evtDelMsg = EventManager.deleteEvent(getGoogleCalObj(), selectedCalId, e.getId());
iEvtCnt++;
}
}
catch(NullPointerException npe)
{
System.out.println("edate is null so creating");
processImportedEventsData();
}
}
}
else
{
System.out.println("no events in this calendar");
}
setInfoMsg("Successfully deleted " + iEvtCnt + " Events out of total " + totalEvents);
createEventFlag = true;
processImportedEventsData();
}
catch (IOException ex)
{
Logger.getLogger(ManageCalendar.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
This one worked for me I simply used the long value of the event's i.e "e" date and time and compared with the todays date time.The getValue() method returns in long which is milliseconds. This made it a bit simple.
And then in the loop i deleted all the events calling deleteEvent() of EventManager.

Related

how to get the Long count value in for each loop from the outside the loop

crashService:
for (CrashReportForChartForm crashReport : crashReportForChartForms) {
//i want to get this count value and send it to else part below
Long count = crashReport.getCount();
Date newDate = new SimpleDateFormat("MM/dd/yyyy").parse(crashReport.getAddedDate());
dates.add(newDate);
}
for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1)) {
// convert local date to date format
Date accdate = java.sql.Date.valueOf(date);
DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
String addDate = date.format(format);
if (!dates.contains(accdate)) {
resultCrashReportForChartForms.add(new CrashReportForChartForm(addDate, new Long(0)));
} else {
//count value should be get from count in crashReport
resultCrashReportForChartForms.add(newCrashReportForChartForm(addDate, count));
}
}
}
}
return resultCrashReportForChartForms;
}
Map<Date,Integer> crashCounts = new HashMap<>();
long count;
for (CrashReportForChartForm crashReport : crashReportForChartForms) {
Date newDate = new SimpleDateFormat("MM/dd/yyyy").parse(crashReport.getAddedDate());
if(crashCounts.containsKey(newDate)){
count=crashCounts.get(newDate)+ crashReport.getCount();
crashCounts.put(newDate,count);
}
else{
crashCounts.put(newDate,crashReport.getCount());
}
}
This will give you the list of crash for particular days. Post this you can run a for loop to check if for a particular date contains no crashes. If there is no crash you can add a dummy record containing a crash count 0.
Use a Map<Date,Long>:
Map<Date,Long> dateCount = new HashMap<>();
for (CrashReportForChartForm crashReport : crashReportForChartForms) {
//i want to get this count value and send it to else part below
Long count = crashReport.getCount();
Date newDate = new SimpleDateFormat("MM/dd/yyyy").parse(crashReport.getAddedDate());
dateCount.put(newDate, count);
}
for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1)) {
// convert local date to date format
Date accdate = java.sql.Date.valueOf(date);
DateTimeFormatter format = DateTimeFormatter.ofPattern("MM/dd/yyyy");
String addDate = date.format(format);
Long count = dateCount.get(accdate);
if (count == null) {
resultCrashReportForChartForms.add(new CrashReportForChartForm(addDate, new Long(0)));
} else {
//count value should be get from count in crashReport
resultCrashReportForChartForms.add(newCrashReportForChartForm(addDate, count));
}
}
}
}
return resultCrashReportForChartForms;
}
UPDATE:
To cumulate the count per date:
Map<Date,Long> dateCount = new HashMap<>();
for (CrashReportForChartForm crashReport : crashReportForChartForms) {
//i want to get this count value and send it to else part below
Date newDate = new SimpleDateFormat("MM/dd/yyyy").parse(crashReport.getAddedDate());
Long count = dateCount.get(newDate);
if (count == null) {
count = crashReport.getCount();
} else {
count += crashReport.getCount();
}
dateCount.put(newDate, count);
}
UPDATE 2:
Note that in the second loop, accdate is actually a java.sql.Date, and I'm not sure it can be used as is to retrieve the count from the map.

Android-Week-View loading events per week asynchronously

First off, I'm using the library https://github.com/alamkanak/Android-Week-View
I have an API returning data for one week at a time.
For example GET /stuff/{current_week_number}
Then a scroll listener set up that checks if the week has changed, and will then load
GET /stuff/{new_week_number}
The problem is that all events will be in the current week position as duplicates. I know the library wants events on a per month basis, is it the problem?
Been debugging this for a day now, help would be greatly appreciated.
Function for creating the event:
private WeekViewEvent createNew(JSONObject json, int week) {
String eventTitle = "";
String colorString = "#999";
String startTimeString = "";
String endTimeString = "";
int dayOfWeek = 0;
try {
eventTitle = json.getString("text").replaceAll("\n", " ");
colorString = json.getString("color");
startTimeString = json.getString("startTime");
endTimeString = json.getString("endTime");
dayOfWeek = json.getInt("day");
} catch (JSONException e) {
e.printStackTrace();
}
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, hoursFromString(startTimeString));
startTime.set(Calendar.MINUTE, minutesFromString(startTimeString));
startTime.set(Calendar.WEEK_OF_YEAR, week);
startTime.set(Calendar.DAY_OF_WEEK, dayOfWeek);
Calendar endTime = (Calendar) startTime.clone();
endTime.set(Calendar.HOUR_OF_DAY, hoursFromString(endTimeString));
endTime.set(Calendar.MINUTE, minutesFromString(endTimeString));
WeekViewEvent event = new WeekViewEvent(mGlobalCounter, eventTitle, startTimeString + " - " + endTimeString, startTime, endTime);
event.setColor(Color.parseColor(colorString));
if (event.getColor() == Color.WHITE) {
event.setColor(R.color.event_color_01);
}
return event;
}
Month change listener + helper method (from example)
private boolean eventMatches(WeekViewEvent event, int year, int month) {
return (event.getStartTime().get(Calendar.YEAR) == year && event.getStartTime().get(Calendar.MONTH) == month - 1) || (event.getEndTime().get(Calendar.YEAR) == year && event.getEndTime().get(Calendar.MONTH) == month - 1);
}
MonthLoader.MonthChangeListener mMonthChangeListener = new MonthLoader.MonthChangeListener() {
#Override
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) {
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<>(); //getEvents(newYear, newMonth);
for (WeekViewEvent event : mNewEvents) {
if (eventMatches(event, newYear, newMonth)) {
events.add(event);
}
}
mFetchedWeeks.add(Integer.valueOf(mWeek));
return events;
}
};
And here's the JSON-response from the API
https://gist.github.com/jonathanort/668de267966e3b673fffe23dfbdfb90b
Also, my modified version of WeekView.java
https://gist.github.com/jonathanort/472d86355dcdbc338f13373a838f548a
The solution was to add the line
startTime.get(Calendar.DAY_OF_WEEK);
before
startTime.set(Calendar.DAY_OF_WEEK, dayOfWeek);
Apparently it will not set the day otherwise

JSpinner time constraint

I am trying to create a spinner that has hours and minutes. The minutes part needs to increment by 10 mins only and the time must range from the current time to an end time. I also need the minimum value (previously current time) to update to current time.
I tried playing around with it, but I just couldn't get it to work.
JSpinner spinner1 = new javax.swing.JSpinner();
SpinnerDateModel spinnermodel = new SpinnerDateModel();
spinnermodel.setCalendarField(Calendar.MINUTE);
spinner1.setModel(spinnermodel);
spinner1.setEditor(new JSpinner.DateEditor(spinner1, "hh:mm"));
SpinnerModel model = new SpinnerDateModel(currentDate, currentDate, latestDate, Calendar.MINUTE * 10 ?);
The SpinnerDateModel just uses 1 to increment the field you want to change.
I extended the SpinnerDateModel to add an addition property to the model to control the increment value instead of hard coding to 1:
import java.util.*;
import javax.swing.*;
public class MySpinnerDateModel extends SpinnerDateModel
{
private int increment = 1;
public MySpinnerDateModel(Date value, Comparable start, Comparable end, int calendarField)
{
super(value, start, end, calendarField);
}
public MySpinnerDateModel()
{
this(new Date(), null, null, Calendar.DAY_OF_MONTH);
}
public void setIncrement(int increment)
{
this.increment = increment;
}
public int getIncrement()
{
return increment;
}
#Override
public Object getNextValue()
{
Calendar cal = Calendar.getInstance();
Date value = (Date)getValue();
cal.setTime(value);
cal.add(getCalendarField(), increment);
Date next = cal.getTime();
Comparable end = getEnd();
return ((end == null) || (end.compareTo(next) >= 0)) ? next : null;
}
#Override
public Object getPreviousValue()
{
Calendar cal = Calendar.getInstance();
Date value = (Date)getValue();
cal.setTime(value);
cal.add(getCalendarField(), -increment);
Date prev = cal.getTime();
Comparable start = getStart();
return ((start == null) || (start.compareTo(prev) <= 0)) ? prev : null;
}
}
You should be able to use the model the way you did before but with one additional statement:
MySpinnerDateModel model = new MySpinnerDateModel(currentDate, currentDate, latestDate, Calendar.MINUTE);
model.setIncrement( 10 );
You can extend the SpinnerDateModel to specify the behavior. Below is an example in which the getNextValue and getPreviousValue are overridden to return values +/- 10 minutes:
Date now = new Date();
Date start = now;
final long tenMinutesInMillis = 1000 * 60 * 10;
Date end = new Date(now.getTime() + tenMinutesInMillis * 60);
SpinnerModel model = new SpinnerDateModel(now, start, end, Calendar.MINUTE){
#Override
public Object getNextValue(){
Date newDate = new Date(getDate().getTime() + tenMinutesInMillis);
Date endDate = (Date)getEnd();
return newDate.getTime() > endDate.getTime() ? endDate : newDate;
}
#Override
public Object getPreviousValue(){
Date newDate = new Date(getDate().getTime() - tenMinutesInMillis);
Date startDate = (Date)getStart();
return newDate.getTime() < startDate.getTime() ? startDate : newDate;
}
};

How to get/compute total number of months using JDateChooser

I'm new to Java
How do I get the total number of months between two (2) jdatechooser? I've search already about this but the date was set to the code, In my case I want to put the dates via JDateChooser.
I can do this through this code but if the year change I was not able to compute the total number of months I want to do this without using JodaTime.
Here is my code
public void month(){
int TotalMonth;
Calendar toDate;
Calendar fromDate;
int increment;
Date dt1 = date1.getDate(); //datechooser 1
Date dt2 = date2.getDate(); //datechooser 2
fromDate = Calendar.getInstance();
toDate = Calendar.getInstance();
if(dt1.after(dt2))
{
fromDate.setTime(dt2);
toDate.setTime(dt1);
}
else
{
fromDate.setTime(dt1);
toDate.setTime(dt2);
}
increment = 0;
TotalMonth = toDate.get(Calendar.MONTH) - (fromDate.get(Calendar.MONTH + increment));
jLabel2.setText(Integer.toString(age));
}
JodaTime is simpler, however...
You need to loop from the start time to the end, incrementing the MONTH field on each loop while the date remains before the end time...
For example...
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal1 = Calendar.getInstance();
cal1.setTime(sdf.parse("08/03/1972"));
Calendar cal2 = Calendar.getInstance();
cal2.setTime(sdf.parse("08/03/2014"));
// Yes, you can use cal1, but I you might want
// to preserve it for other reasons...
Calendar cal3 = Calendar.getInstance();
cal3.setTime(cal1.getTime());
int months = 0;
while (cal3.before(cal2)) {
cal3.add(Calendar.MONTH, 1);
months++;
}
System.out.println("Months = " + months);
} catch (ParseException exp) {
exp.printStackTrace();
}
Prints out Months = 505.
If you change cal2 to 08/04/1972, it will print Months = 1

Date validation to be less than 18 years from current date in android

I have to do a validation in Date field which must be 18 years less than current date else it must show error.
public static boolean dobdateValidate(String date) {
boolean result = false;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
try {
Date parseddate = sdf.parse(date);
Calendar c2 = Calendar.getInstance();
c2.add(Calendar.DAY_OF_YEAR, -18);
Date dateObj2 = new Date(System.currentTimeMillis());
if (parseddate.before(c2.getTime())) {
result = true;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
you can use this method to get age
/**
* calculates age from birth date
*
* #param selectedMilli
*/
private void getAge(long selectedMilli) {
Date dateOfBirth = new Date(selectedMilli);
Calendar dob = Calendar.getInstance();
dob.setTime(dateOfBirth);
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.MONTH) < dob.get(Calendar.MONTH)) {
age--;
} else if (today.get(Calendar.MONTH) == dob.get(Calendar.MONTH)
&& today.get(Calendar.DAY_OF_MONTH) < dob
.get(Calendar.DAY_OF_MONTH)) {
age--;
}
if (age < 18) {
//do something
} else {
}
str_age = age + "";
Log.d("", getClass().getSimpleName() + ": Age in year= " + age);
}
The core issue is that Calendar.DAY_OF_YEAR is not correct as "[DAY_OF_YEAR indicates] the day number within the current year".
Use Calendar.YEAR instead.
Other suggestions:
The dateObj2 variable is never used and should be removed.
Return directly instead of using an intermediate flag variable.
Take in a Date/Calendar object and leave the caller responsible for parsing.

Categories