I want to make an offline daily gift system. How can I do it.
date = new Date();
calendarG = new GregorianCalendar();
calendarG.setTime(date);
if(!prefs.contains("lastloginday"))
prefs.putInteger("lastloginday", calendarG.get(Calendar.DAY_OF_MONTH));
if (calendarG.get(Calendar.DAY_OF_MONTH) - 1 == prefs.getInteger("lastloginday")) {
prefs.putInteger("lastloginday", calendarG.get(Calendar.DAY_OF_MONTH));
prefs.putInteger("dailyCombo", prefs.getInteger("dailyCombo") + 1);
prefs.putInteger("Coin", prefs.getInteger("Coin") + prefs.getInteger("dailyCombo") * 25);
}else{
prefs.putInteger("lastloginday", calendarG.get(Calendar.DAY_OF_MONTH));
}
This code is not useful in different months.
You can do in this way :
Preferences preferences=Gdx.app.getPreferences("MyPref");
String LAST_LOGIN_DAY="lastloginday";
GregorianCalendar calendarG = new GregorianCalendar();
calendarG.setTime(new Date());
if(!preferences.contains(LAST_LOGIN_DAY)) {
//first day in App
preferences.putInteger(LAST_LOGIN_DAY, calendarG.get(Calendar.DAY_OF_YEAR));
preferences.flush();
}
if(preferences.getInteger(LAST_LOGIN_DAY)-1==calendarG.get(Calendar.DAY_OF_YEAR)){
//next loginday up to a year
updateValue(preferences,calendarG);
}else{
if(calendarG.get(Calendar.DAY_OF_YEAR)==1) {
// check for the 1st day of the year
boolean isLeap = calendarG.isLeapYear(calendarG.get(Calendar.YEAR));
if (isLeap && preferences.getInteger(LAST_LOGIN_DAY)==366 ) {
updateValue(preferences,calendarG);
}else if(preferences.getInteger(LAST_LOGIN_DAY)==365){
updateValue(preferences,calendarG);
}
else
preferences.putInteger(LAST_LOGIN_DAY,calendarG.get(Calendar.DAY_OF_YEAR));
}
else
preferences.putInteger(LAST_LOGIN_DAY,calendarG.get(Calendar.DAY_OF_YEAR));
}
Here is update method :
public void updateValue(Preferences preferences,GregorianCalendar calendarG){
preferences.putInteger(LAST_LOGIN_DAY,calendarG.get(Calendar.DAY_OF_YEAR));
preferences.putInteger("dailyCombo", preferences.getInteger("dailyCombo",0) + 1);
preferences.putInteger("Coin", preferences.getInteger("Coin",0) + preferences.getInteger("dailyCombo",0) * 25);
preferences.flush();
}
Related
/** Reports whether or not date1 comes earlier in time than date2. For example, isEarlierThan("12-01-2015",
"02-15-2017") is true but isEarlierThan("10-11-2016", "10-11-2016") and isEarlierThan("09-09-1967", "02-15-1933")is false.
* /
public static boolean isEarlierThan (String date1, String date2)
{
if(date1.compareTo(date2) > 0) {
return true;
}
else if (date1.compareTo(date2) <= 0) {
return false;
}
else {
return true;
}
}
This code works sometimes but no always. I have ran a tests case and it fails. The following test case is below.
public void testIsEarlierThan ()
{
assertTrue(isEarlierThan("12-01-2015", "02-15-2017"));
assertFalse(isEarlierThan("10-11-2016", "10-11-2016"));
assertFalse(isEarlierThan("09-09-1967", "02-15-1933"));
assertTrue(isEarlierThan("02-14-2017", "02-15-2017"));
}
When I run the test case, only the first two work then it stops at the third one. But I don't understand whats wrong? if the first one works shouldn't the third one work just fine? Thanks in advance!
Answering my own question. And for future reference if anyone has a similar question.
public static boolean isEarlierThan (String date1, String date2)
{
String month1 = date1.substring(0, 2);
String month2 = date2.substring(0, 2);
String day1 = date1.substring(3, 5);
String day2 = date2.substring(3, 5);
String year1 = date1.substring(6, 10);
String year2 = date2.substring(6, 10);
date1 = year1 + month1 + day1; // + month1 + day1
date2 = year2 + month2 + day2; // + month2 + day2
if (date1.compareTo(date2) < 0)
{
return true;
}
else if (date1.compareTo(date2) > 0)
{
return false;
}
else
{
return false;
}
}
Basically I have a method that takes the two dates, takes them apart into a year, a month, and a day. Then puts them back together in a different order so that when I compare them it will print the which true if date1 is before date2 or false if date1 is after or equal to date2.
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
I want the code to trigger the JOptionPane.
Here is the code for the working clock:
new Thread() {
public void run() {
while (true) {
GregorianCalendar cal = new GregorianCalendar();
int hour = cal.get(GregorianCalendar.HOUR);
int min = cal.get(GregorianCalendar.MINUTE);
int sec = cal.get(GregorianCalendar.SECOND);
int AM_PM = cal.get(GregorianCalendar.AM_PM);
String day_night;
if (AM_PM == 1) {
day_night = "PM";
} else {
day_night = "AM";
}
String time = hour + ":" + min + ":" + sec + " " + day_night;
lblClock.setText(time);
}
}
}.start();
Here is code I wrote to trigger alarm, but no 'play sound' is coded yet, because I can't even get the JOptionPane to appear. Why? I want to get the values from spinners, than compare to real time until they meet and than trigger alarm and exit thread. How to fix it?
btnAlarm.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
new Thread() {
public void run() {
txtAlarmSet.setVisible(true);
boolean flag = false;
GregorianCalendar g = new GregorianCalendar();
int hour = Integer.parseInt(spinnerHour.getModel().getValue().toString());
int minute = Integer.parseInt(spinnerMinute.getModel().getValue().toString());
int second = Integer.parseInt(spinnerSecond.getModel().getValue().toString());
int AMorPM;
if (rdbtnAm.isSelected()) {
AMorPM = 0;
} else
AMorPM = 1;
while (flag == false) {
int realHour = g.get(GregorianCalendar.HOUR);
int realMinute = g.get(GregorianCalendar.MINUTE);
int realSecond = g.get(GregorianCalendar.SECOND);
int realAM_PM = g.get(GregorianCalendar.AM_PM);
if (hour == realHour && minute == realMinute && second == realSecond
&& AMorPM == realAM_PM) {
JOptionPane.showMessageDialog(null, "WORKS!"); // <- this doesn't appear!
flag = true;
}
}
txtAlarmSet.setVisible(false);
}
}.start();
}
});
In your checking loop, you need to reacquire the Calendar on every pass, otherwise, you'll just end up re-checking the same time value over and over. Move the line
GregorianCalendar g = new GregorianCalendar();
inside the loop.
Note: This is not a particularly good approach to this problem. What you're doing is called "busy waiting" and it's generally not good for much other than making the CPU get hot. A better approach would be to use an event-driven approach, but that's beyond the scope of this answer.
One major problem I notice is missing } after AMorPM = 1; making it impossible to work for AM.
I'm trying to check a current date and time is in between Friday 17:42 and Sunday 17:42 of the week with Java.
At the moment I'm doing this with really really bad code block. It was a hurry solution. Now I'm refactoring but I couldn't find any method in joda or etc.
Any ideas?
Thanks
private final Calendar currentDate = Calendar.getInstance();
private final int day = currentDate.get(Calendar.DAY_OF_WEEK);
private final int hour = currentDate.get(Calendar.HOUR_OF_DAY);
private final int minute = currentDate.get(Calendar.MINUTE);
if (day != 1 && day != 6 && day != 7) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else {
if (day == 6 && hour > 16) {
if (hour == 17 && minute < 43) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else {
return badge == 0;
}
} else if (day == 6 && hour < 17) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else if (day == 1 && hour > 16) {
if (hour == 17 && minute < 43) {
return badge == 0;
} else {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
}
} else {
return badge == 0;
}
}
I've used the solution like thiswith the help of #MadProgrammer and #Meno Hochschild
Method:
public static boolean isBetween(LocalDateTime check, LocalDateTime startTime, LocalDateTime endTime) {
return ((check.equals(startTime) || check.isAfter(startTime)) && (check.equals(endTime) || check.isBefore(endTime))); }
Usage:
static LocalDateTime now = LocalDateTime.now();
static LocalDateTime friday = now.with(DayOfWeek.FRIDAY).toLocalDate().atTime(17, 41);
static LocalDateTime sunday = friday.plusDays(2).plusMinutes(1);
if (!isBetween(now, friday, sunday)) { ... }
Thanks again for your efforts.
Date and Calendar have methods that can perform comparisons on other instances of Date/Calendar, equals, before and after
However, I'd encourage the use of Java 8's new Time API
public static boolean isBetween(LocalDateTime check, LocalDateTime startTime, LocalDateTime endTime) {
return ((check.equals(startTime) || check.isAfter(startTime)) &&
(check.equals(endTime) || check.isBefore(endTime)));
}
Which will return true if the supplied LocalDateTime is within the specified range inclusively.
Something like...
LocalDateTime start = LocalDateTime.now();
start = start.withDayOfMonth(26).withHour(17).withMinute(42).withSecond(0).withNano(0);
LocalDateTime end = start.plusDays(2);
LocalDateTime check = LocalDateTime.now();
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = start;
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = end;
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = start.plusDays(1);
System.out.println(check + " is within range = " + isBetween(check, start, end));
check = end.plusMinutes(1);
System.out.println(check + " is within range = " + isBetween(check, start, end));
Which outputs
2015-06-25T18:31:32.969 is within range = false
2015-06-26T17:42 is within range = true
2015-06-28T17:42 is within range = true
2015-06-27T17:42 is within range = true
2015-06-28T17:43 is within range = false
Joda-Time has an Interval class which makes it even eaiser
Interval targetInterval = new Interval(targetStart, targetEnd);
System.out.println("Contains interval = " + interval.contains(targetInterval)
which is demonstrated here
A different approach...
So I was thinking on way home, assuming all you have is the date/time you want to check, how you might determine if the day falls within your range
LocalDateTime now = LocalDateTime.now();
boolean isBetween = false;
switch (now.getDayOfWeek()) {
case FRIDAY:
case SATURDAY:
case SUNDAY:
LocalDateTime lastFriday = getLastFriday(now);
LocalDateTime nextSunday = getNextSunday(now);
isBetween = isBetween(now, lastFriday, nextSunday);
System.out.println(lastFriday + " - " + nextSunday + ": " + end);
break;
}
What this does is checks the dayOfWeek to see if it's within the desired range, if it is, it finds the previous Friday and next Sunday from the specified date and checks to see if it falls between them (see the previous example)
lastFriday and nextSunday simply adds/subtracts a day from the specified date/time until to reaches the desired dayOfWeek, it then seeds the required time constraints
public static LocalDateTime getLastFriday(LocalDateTime anchor) {
LocalDateTime ldt = LocalDateTime.from(anchor);
return ldt.with(DayOfWeek.FRIDAY).withHour(17).withMinute(42).withSecond(0).withNano(0);
}
public static LocalDateTime getNextSunday(LocalDateTime anchor) {
LocalDateTime ldt = LocalDateTime.from(anchor);
return ldt.with(DayOfWeek.SUNDAY).withHour(17).withMinute(42).withSecond(0).withNano(0);
}
With Calendar you can know what DAY_OF_WEEK is the given date, then simply check the hours:
Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// in friday the hour must be greater than 17:42
if (dayOfWeek == 5 && ((hour > 17) || (hour == 17 && minute >= 42)) {
// successss!!
}
// days from 1 to 7... saturday(6) all day
if (dayOfWeek == 6) {
// successss!!
}
// sunday hour must be lower than 17:42
if (dayOfWeek == 7 && ((hour < 17) || (hour == 17 && minute <= 42)) {
// successss!!
}
A better solution using old Java would look like this:
// current timestamp
GregorianCalendar gcal = new GregorianCalendar();
// specify ISO-week (you are searching for friday until sunday in this order)
gcal.setMinimalDaysInFirstWeek(4);
gcal.setFirstDayOfWeek(Calendar.MONDAY);
// sunday at 17:43
GregorianCalendar sunday = (GregorianCalendar) gcal.clone();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
sunday.set(Calendar.HOUR_OF_DAY, 17);
sunday.set(Calendar.MINUTE, 43);
sunday.set(Calendar.SECOND, 0);
sunday.set(Calendar.MILLISECOND, 0);
// friday at 17:42
GregorianCalendar friday = (GregorianCalendar) sunday.clone();
friday.add(Calendar.DATE, -2);
friday.add(Calendar.MINUTE, -1);
// logging for test purposes
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println(f.format(friday.getTime()));
System.out.println(f.format(gcal.getTime()));
System.out.println(f.format(sunday.getTime()));
// result (assumption: half-open-interval)
boolean withinTimeWindow = !gcal.before(friday) && gcal.before(sunday);
Java-8 offers a shorter approach (assuming ISO-weekmodel):
LocalDateTime now = LocalDateTime.now();
LocalDateTime friday = now.with(DayOfWeek.FRIDAY).toLocalDate().atTime(17, 42);
LocalDateTime sunday = friday.plusDays(2).plusMinutes(1);
boolean withinTimeWindow = !now.isBefore(friday) && now.isBefore(sunday);
Finally your equivalent evaluation can look like this:
if (!withinTimeWindow) {
if (combined != 0) {
return badge == 1;
} else {
return badge == product;
}
} else {
return badge == 0;
}
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.