I have built a function to return me a date (as a String) providing the week number and the day.
My function is working perfectly on my device (Samsung Galaxy S6 under LineageOS android 7.1.2), but one of my friend, using another android device (android 5.1.x, that's all I know), reported me an error : the function returns him a date in the current week (the week of the real time when the function is called) whatever the week number he give.
To not bother my friends, I'm using an emulator that have the same problem. It's the default one in Android studio (Emulator Nexus_5_API_23 android 6.0).
Here is my function :
public static String getDayString(int weekNumber, int dayPosition) {
DateFormat sdf = DateFormat.getDateInstance();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
cal.set(Calendar.DAY_OF_WEEK, dayPosition + 2);
return sdf.format(cal.getTime());
}
In my first attempts to understand the problem, I discovered that cal.set(Calendar.WEEK_OF_YEAR, weekNumber); wasn't working.
Then I putted Log.d("ClassName", String.valueOf(cal.get(Calendar.WEEK_OF_YEAR))); to see if the week number was properly changed from the current week number (set by getInstance()) to the desired week number (weekNumber). But the problem disappeared and the function was working perfectly...
It turns out that when I put cal.get(Calendar.WEEK_OF_YEAR); right after cal.set(Calendar.WEEK_OF_YEAR, weekNumber); the week number is updated but cal.set(...) alone is not working.
Here is my "fixed" function :
public static String getDayString(int weekNumber, int dayPosition) {
DateFormat sdf = DateFormat.getDateInstance();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
cal.get(Calendar.WEEK_OF_YEAR);
cal.set(Calendar.DAY_OF_WEEK, dayPosition + 2);
return sdf.format(cal.getTime());
}
I'm extremely surprised and confused by this result. How cal.get(...) can change anything ? How I can find another way to fix this "problem" ? What is the problem with the cal.set(...) method ? Did I do something wrong or am I missing something ?
This strange "quantum observer effect" problem doesn't appear to be present in Java in general. But only on some (not all) android devices.
Related
I have a current date in Java like below:
String currentDate = CoreUtil.parseDate(new Date());
This returns the date for today in the form 2019-03-26.
I declared another date so that it should automatically add 7 days to the current date like below:
String defaultendDate=CoreUtil.parseDate(new Date()); + 7 days //example
So the defaultEnddate should be 2019-04-03
How would I accomplish this as I don't want to use any simple date formatter?
Also, I would like to store the date as it is in String for reasons and secondly, I only want date, not the time. I am not using Java 8 as well, so I can't really use LocalDate library here.
LocalDate is perfect for this job:
LocalDate.now().plusDays(7);
You can get your string representation with
.format(DateTimeFormatter.ISO_DATE);
If you're not able to use Java 8, then you have a few options:
Use the ThreeTen-Backport, which backports most functionality of the Java 8 JSR-310 API, normally available in the java.time package. See here for details. This package is available in Maven Central.
You can also use Joda Time. The peculiar thing is that these two projects have almost the same layout of their websites.
If you're otherwise not able to use ThreeTen-Backport or Joda Time, you can use this:
Calendar c = GregorianCalendar.getInstance();
c.add(Calendar.DATE, 7);
String s = new SimpleDateFormat("yyyy-MM-dd")
.format(c.getTime());
Warning
Many things are wrong with the old Date and Time API, see here. Use this only if you have no other option.
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 7);
Date defaultEndDate = cal.getTime();
Something like
LocalDate.now().plusWeeks(1);
would also do the cause.
Please, bare in mind using Java 8 Date/Time API for any operations with dates and times. as it addresses shortcomings of old Date and Calendar regarding thread safety, code design, time-zone logic and other.
UPDATE:
If you must use old Date/Time API, following code would suffice:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("Adding seven days: " + calendar.getTime());
date = calendar.getTime();
//your code
String currentDate = CoreUtil.parseDate(new Date());
*
String dt = new SimpleDateFormat("yyyy.MM.dd").format(new Date()); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 7); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
System.out.println(dt);
*
Use java.util.Date try this one
I updated to Android Wear 2.0 today. My watch face, developed by myself, now shows ", 005 14". Before the update, it had said "Sun, May 14".
The code which gets the date format:
String pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, "EEEddMMM");
delegate = new SimpleDateFormat(pattern);
delegate.setCalendar(calendar);
From debugging, the value it fetched was "EEE, MMM dd".
The code which does the actual formatting:
calendar.set(Calendar.DAY_OF_WEEK, time.getDayOfWeek() + 1);
calendar.set(Calendar.DAY_OF_MONTH, time.getDayOfMonth());
// Android hard-codes in a + 1 when formatting as a number.
calendar.set(Calendar.MONTH, time.getMonthOfYear() - 1);
return delegate.format(dummyDate);
I checked the current docs for SimpleDateFormat and both E and M are still supposedly supported. So is Wear 2.0 just broken?
I figure for later API versions it might be possible to work around this by using the android.icu alternative. But this means supporting both the old and new code indefinitely, so if it turns out that it's something they're planning to fix in the platform, I'd rather not waste any more time.
In many posts and even on Google's site (here) I've seen this code :
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
So I tested it in a standalone Java program (non Android) :
Calendar c = Calendar.getInstance();
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new Date(System.currentTimeMillis())));
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new Date(c.getTimeInMillis())));
Output :
01:23:33.884
01:23:33.876
It works fine without setting the time with setTimeInMillis explicitly.
What's the point of calendar.setTimeInMillis(System.currentTimeMillis()) ?
Is it erroneous, esp. in Android programming, to not set it this way ?
I need some help to be able to set the first day of week from Sunday to Monday (change SMTWTFS to MTWTFSS) in com.toedter.calendar.JDateChooser, I tried like this with no result, I'm using version 1.3.3 of JDateChooser:
JDateChooser dateChooser = new JDateChooser(new Date());
dateChooser.getCalendar().setFirstDayOfWeek(Calendar.MONDAY);
Following the conventions of proper getter implementation, getCalendar() probably returns a copy of the calendar used. Therefore your call to setFirstDayOfWeek() is on an object that is not the calendar object of your JDateChooser.
I can't seem to find the documentation for JDateChooser 1.3.3, but if setCalendar() exists, this should work:
Calendar c = dateChooser.getCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
dateChooser.setCalendar(c);
In my project I am saving milliseconds in a sqllite databse, by default I am saving
System.currentTimeMillis()
in the database, but there is an option for the user to select previous date from a date picker? But what sould I save then when user selects a previous or up comming days from the date picker? How can I get that day as a long(milliseconds) format?
Create a Calender instance and set the date you want. Then call calendar.getTimeInMillis();. See the answer of this previous SO question for more information.
EDIT To set the calendar date you can use something like this:
//Lets suppose you have a DatePicker instance called datePicker
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
cal.set(Calendar.MONTH, datePicker.getMonth());
cal.set(Calendar.YEAR, datePicker.getYear());
See the Calendar class for more information.
I was looking for a similar solution for a javase scenario when I came across this answer. I made a little modification to Angelo's answer to make my own case work, and it gave me exactly what I was looking for. To make things a little more interesting, I created a method that can be reused.
class Controller {
public static Calendar cal = Calendar.getInstance();
public static long getEpoch_fromDatePicker( DatePicker datePicker ) {
Controller.cal.set(Calendar.DAY_OF_MONTH, datePicker.getValue().getDayOfMonth() );
Controller.cal.set(Calendar.MONTH, datePicker.getValue().getMonthValue() );
Controller.cal.set(Calendar.YEAR, datePicker.getValue().getYear() );
return Controller.cal.getTimeInMillis() /1000;
}
}
Someone might find this useful