How to calculate difference between two date from DatePicker widget - java

I've a problem with my GWT project: i'm only interested to calculate the difference between two date (in days) from two DatePicker Widget.
This is my code, i take it mainly from here: http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/datepicker/client/DatePicker.html
// Create a date picker "FROM: "
final DatePicker datePicker1 = new DatePicker();
datePicker1.addValueChangeHandler(new ValueChangeHandler<Date>() {
public void onValueChange(ValueChangeEvent<Date> event) {
Date date1 = datePicker1.getValue();
}
});
// Set the default value
datePicker1.setValue(new Date(), true);
// Create a date picker "TO: "
final DatePicker datePicker2 = new DatePicker();
datePicker2.addValueChangeHandler(new ValueChangeHandler<Date>() {
public void onValueChange(ValueChangeEvent<Date> event) {
Date date2 = datePicker2.getValue();
}
});
// Set the default value
datePicker2.setValue(new Date(), true);
// =================DEBUG===================
Button send = new Button("send", new ClickHandler(){
public void onClick(ClickEvent event) {
//calculate difference between date1 and date2
days = (int) CalendarUtil.getDaysBetween(date1, date2);
Window.alert("Differece: " + days);
}
});
but while i have no error in eclipse, when i run the web application i have this error:
[ERROR] [progetto] Uncaught exception escaped
com.google.gwt.event.shared.UmbrellaException: Exception caught: null
[...]
I can write more error details if necessary but it's very long...
Can you tell me how to fix this error or how to calculate it with an alternative methods?
Thank you in advance.

it seems to me one of your object is null. look into exception under this exception, there would be more detail. Second tell me where are you calculating days in code and how? if you share more code it would be helpful. But I think you look for date1 and date2 for null. If you can please share more code, i will be more helpful and do the debugging keeping this in mind.

Related

how to show error if on device time does not match with internet time in android studio like WhatsApp

im making an android app which shows time of upload relative to the device time, but if the device time and date is not set correct then I do not get the desired result. so how to show warning or error if the device time and date is not correct or matches to the internet time. the app should not work unless the user set the date and time correct.
Get an extra UTC DateTimeOffset parameter as a response from the uploaded API & then convert it into your local timezone.
Cons -
If time is set wrong in the device, you have to create a localization method for it which can convert the timestamp to proper time without interfering with the local timezone.
You can use static timezoneid for conversion or get it by internal API calls, I uses Xamarin soo for me it's like -
var timeZoneId = "Asia/Calcutta"; // use it for worldwide application usage TimeZoneInfo.Local.ToString();
DateTime localizedDateTime = TimeZoneInfo.ConvertTimeFromUtc(incomingDATE.ToUniversalTime(), TimeZoneInfo.FindSystemTimeZoneById(timeZoneId));
Soo convert the received UTC DateTimeOffset to Localized time.
This thing works best for my apps. I use jsoup to search the google time and gets current time and then I compare the phone time with google time. So if these time are different you can stop user using a dialogbox or alertbox to tell them the times have changed. You can implement in MainActivity to check this condition.
Here is a snippet so you get the idea more clearly.
public class HomeActivity extends AppCompatActivity {
//phoneDate and phoneTime to get current phone date and time
String phoneDate = new SimpleDateFormat("dd MMM yyyy ").format(clnd.getTime()).trim();
String phoneTime = new SimpleDateFormat("hh:mm a").format(clnd.getTime()).trim();
String googleDate;
String googleTime ;
#Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.home);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//URL to search time
String url = "https://www.google.co.in/search?q=time";
Document document = Jsoup.connect(url).get();
org.jsoup.select.Elements time = document.getElementsByClass("gsrt vk_bk FzvWSb YwPhnf");
org.jsoup.select.Elements date = document.getElementsByClass("KfQeJ");
Log.d("HTML", "google date" + String.format(date.text()));
Log.d("HTML", "google time" + time.text());
googleDate = date.text().trim();
googleTime = time.text().trim();
//'0'is not present when hour is single digit
char second = googleTime.charAt(1);
if(second == ':'){
googleTime = "0" + googleTime;
}
Log.d("Proper format", "google time" + googleTime);
Log.d("Date", "your current url when webpage loading.." + phoneDate);
Log.d("Time", "your current url when webpage loading.." + phoneTime);
if(googleDate.contains(phoneDate) && googleTime.equals(phoneTime)){
Log.d("Time", "your current url when webpage loading.." + " true");
}else{
Log.d("Time", "your current url when webpage loading.." + " false");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}

How to create new event in Google Calendar API with java in NetBeans

I followed the quickstart guide that Google provides on Calendar API https://developers.google.com/google-apps/calendar/quickstart/java but they dont explain how to create a new event. I found this snippet of code online
public void createEvent(Calendar cal){
Event event = new Event();
event.setSummary("Event name here");
event.setLocation("event place here");
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + 3600000);
DateTime start = new DateTime(startDate, TimeZone.getTimeZone("UTC"));
event.setStart(new EventDateTime().setDateTime(start));
DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
event.setEnd(new EventDateTime().setDateTime(end));
Event createdEvent = cal.events().insert("primary", event).execute();
System.out.println("Created event id: " + createdEvent.getId());
}
But it didn't help me, i got an error in the Event createdEvent = cal.events() section as events() doesn't exist. Any help is much appreciated, thank you.
At the bottom of your link to the documentation there is a link to Create Events. I won't duplicate the entire page here, but the gist is that you need to Create an Event object (perhaps called MyNewEvent), populate it, and then call:
MyNewEvent = service.events().insert("Some Calendar Id", MyNewEvent).execute();

java.text.ParseException: Unparseable date: "" (at offset 0) error for timepickerdialog

Hi this is my first time developing an simple Android-based application. I need to validate my starting time and ending time, which means ending time must not be less than or equal to starting time. I'm using an EditText to prompt a timepicker dialog. I had tried this code but it doesn't work, in terms of getting the error above at the line below
Date endTimeDate = format.parse(inputEndTime.getText().toString());
This is the whole code of the OnClickListener for EditText field to prompt out a timepicker dialog. I even tried to reverse the statements in if-else but it doesn't work for me too. Anyone can help me in this. Really thanks a lot!
inputEndTime.OnClickListener code:
inputEndTime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
int hour = myTime.get(Calendar.HOUR_OF_DAY);
int min = myTime.get(Calendar.MINUTE);
TimePickerDialog myEndTimePickerDialog = new TimePickerDialog(ViewDocActivity.this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
try
{
Date startTimeDate = format.parse(inputTime.getText().toString());
Date endTimeDate = format.parse(inputEndTime.getText().toString());
if (startTimeDate.compareTo(endTimeDate) <= 0)
{
Context timeContext = getApplicationContext();
CharSequence text = "Please enter the correct end time";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(timeContext, text, duration);
toast.show();
}
else
{
inputEndTime.setText(String.format("%02d:%02d", hourOfDay, minute));
}
}
catch(ParseException e)
{
e.printStackTrace();
}
}
}, hour, min, true);
myEndTimePickerDialog.setTitle("Select Time");
myEndTimePickerDialog.show();
}
});
The reason for your error is, that you are trying to parse the time from your EditText (inputEndTime), but that is empty at the time you do the format.parse().
As you set this up, you have an EditText and a TimePickerDialog. Now you are implementing the TimePickerDialog.OnTimeSetListener#onTimeSet() method. Here you get the time, the user selected in the dialog via the hourOfDay and minute parameters of the method. At this point you have the time, but it not yet written in the EditText field itself.
So the simplest solution to get your code working would be to set that time in your EditText field before doing anything further. To do so, add the following line as the first line of the onTimeSet() method:
inputEndTime.setText(String.format("%02d:%02d", hourOfDay, minute));
This sets the picked time as text in the EditText field in a format that can then be parsed with format.parse(...) later on.
I think you has to format string before format to Date
Maybe trim().
Date startTimeDate = format.parse(inputTime.getText().toString().trim());
Date endTimeDate = format.parse(inputEndTime.getText().toString().trim());

SmartGwt: add days to date

How do you add days to a date in SmartGwt. I found this question and found that I can use CalendarUtil.addDaysToDate(dateToAddTo, daysToAddToDateAsInteger)); but addDaysToDate() is static void. What is the point of a method that can "add days to a date" if it does not return anything?
How do I use this method? I want to do something like this.
Date newDate = dateToAddTo + daysToAddToDate;
Here is a simplified version of my code.
if (listGridRecord.getAttribute("expirationDays") != null) {
CalendarUtil.addDaysToDate((Date) endDate.getValue(), Integer.parseInt(listGridRecord.getAttribute("expirationDays")));
listGridRecord.setAttribute("expirationDate", (Date) endDate.getValue());
} else {
listGridRecord.setAttributeAsJavaObject("expirationDate", null);
}
Here is a link to the javadocs
This method changes the object that is passed as parameter.
Date date = new Date();
long checkBeforeChange = date.getTime();
CalendarUtil.addDaysToDate(date, 1);
long checkAfterChange = date.getTime();
if(checkBeforeChange != checkAfterChange)
Window.alert("It works ;)");
Your code should be something like that:
if (listGridRecord.getAttribute("expirationDays") != null) {
Date tmpDate = endDate.getValue();
CalendarUtil.addDaysToDate(tmpDate, Integer.parseInt(listGridRecord.getAttribute("expirationDays")));
listGridRecord.setAttribute("expirationDate", tmpDate);
} else {
listGridRecord.setAttributeAsJavaObject("expirationDate", null);
}
When doing (Date) endDate.getValue() you get a copy of Date object thus you don't see any change.
I figured out what I was doing wrong with the help of #Adam. I created a new Date variable called expireationDate and set it to (Date) endDate.getValue(); after this I used it to do the calculation.
if (listGridRecord.getAttribute("expirationDays") != null) {
Date expirationDate = (Date) endDate.getValue();
CalendarUtil.addDaysToDate(expirationDate, Integer.parseInt(listGridRecord.getAttribute("expirationDays")));
listGridRecord.setAttribute("expirationDate", expirationDate);
} else {
listGridRecord.setAttributeAsJavaObject("expirationDate", null);
}
First of all, you can wrap all those utility methods you need in your own utility class (private constructor), where e.g. MyDateUtilsClassName.addDays(Date, int) will return new instance, leave parameter unmodified.
When it comes to Date manipulation, in Gwt you can use standard java.util.Date methods, even those deprecated ones like setMinutes, setHours etc. Even when you see com.google.gwt.user.datepicker.client.CalendarUtil method, they are used there.
If it's not server side, but client side, you should not care much about #Deprecated on those methods. Gwt compiles them to javascript anyway. You should be aware of java.util.Calendar. As far as I remember, it is not supported at all.

Detect if current time is between two set up times

I've a program which includes service. This program has settings which allows user to set up, disable and enable time. Between these two times (if option is enabled of course), the program should not work.
I'm actually having hard time to do this. I've already sucessfully converted "disabled" and "enabled" time in milliseconds. I have following code but it doesn't work as expected. I want to detect if current time is between two set up times, so i can disable service at that time.
public boolean isCurrentTimeBetween_enableDisable() {
long sysTime = System.currentTimeMillis();
if((sysTime > disableTime && sysTime < enableTime)) {
return true;
}
return false;
}
Anyone can give me better hint?
UPDATE:
If user selects lets say
Disable hour: 15:00
Enable hour: 22:00
Then code work as expected.
But if user selects lets say:
Disable hour: 22:00
Enable hour: 06:00
Then its obviously that Enable hour is the NEXT day. So i wrote the following code:
if(todaysDisableDate(context).getTime() > enableAt.getTime()) {
enableCal.add(Calendar.DAY_OF_MONTH, 1);
enableAt = formatEnableDate.parse(enableCal.get(Calendar.DAY_OF_MONTH) + "-" +(enableCal.get(Calendar.MONTH)+1) + "-" + enableCal.get(Calendar.YEAR) + " " + endHours_string + ":" + endMinutes_string);
}
Code below is getting the actual date.
public Date todaysDisableDate(Context context) {
Calendar disableCal = Calendar.getInstance();
getTimeValues_preferences((ContextWrapper) context, true, false); // this only gets a string for hour and minute (which is set up in preferences )
Date disableAt = null;
try {
disableAt = formatDisableDate.parse(disableCal.get(Calendar.DAY_OF_MONTH)+"-"+(disableCal.get(Calendar.MONTH)+1)+"-"+disableCal.get(Calendar.YEAR)+" "+startHours_string+":"+startMinutes_string); // današnji datum z današnjo uro
} catch (ParseException e) {
e.printStackTrace();
}
return disableAt;
}
public Date todaysEnableDate(Context context) {
Calendar enableCal = Calendar.getInstance();
getTimeValues_preferences((ContextWrapper) context, false, true);
Date enableAt = null;
try {
enableAt = formatEnableDate.parse(enableCal.get(Calendar.DAY_OF_MONTH)+"-"+(enableCal.get(Calendar.MONTH)+1)+"-"+enableCal.get(Calendar.YEAR)+" "+endHours_string+":"+endMinutes_string); // današnji datum z današnjo uro
if(todaysDisableDate(context).getTime() > enableAt.getTime()) {
enableCal.add(Calendar.DAY_OF_MONTH, 1);
enableAt = formatEnableDate.parse(enableCal.get(Calendar.DAY_OF_MONTH)+"-"+(enableCal.get(Calendar.MONTH)+1)+"-"+enableCal.get(Calendar.YEAR)+" "+endHours_string+":"+endMinutes_string);
}
} catch (ParseException e) {
}
return enableAt;
}
Code is working fine if service starts before 00:00. But if the service starts after midnight (of next day), then i'm getting false from method isCurrentTimeBetween_enableDisable(), because methods todaysDisableDate(Context context) and todaysEnableDate(Context context) are pulling out the next day (the same day as system hour is in)
Do you have to compare dates in your code? If that's a project requirement then you can ignore the following.
Otherwise, I think you can use AlarmManager to create the feature without actually comparing the date. You can create a "Enable" intent and a "Disable" intent for the AlarmManager to fire at the scheduled time. Something like this:
Register your alarms when the user confirmed the time schedule.
Intent intent = new Intent(context, yourAlarmReceiver.class); //or implicit with action
PendingIntent pIntent = PendingIntent.getBroadcast(
context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating (typeConstant, triggerAtMillis, intervalMillis, pIntent);
You just need to figure out what triggerAtMillis is to determine the first shot of that broadcast, and intervalMillis will be a full day, which is a constant in the AlarmManager class.
Setup your custom receiver class (which I wrote as yourAlarmReceiver) which should extend BroadcastReceiver, and register the receiver in your service. In the onReceive() you should perform the corresponding actions based on intent.getAction(). Don't forget to register your receiver with an intent filter if you want more customization.
#Override
public void onReceive(Context context, Intent intent) {
switch(intent.getAction()){
case "enable": //enable if not enabled
case "disable": //disable if not disabled
default: break;
}
}
In this way it may save you some time from struggling with comparing today and tomorrow. You can determine the time of the very first shot by getting the current system time, probably in 24-hour format, and determine if your intended time has already passed. Whether it's been passed, you just need to set the initial firing time to currentTime + difference.
Hope it will shed some light.
I would recommend you to use the start date and end date itself...and not convert them to miliseconds. But this is only if you're not sure.
private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates(){
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
//This is where you determine if the date is inbetween
}
}
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}

Categories

Resources