Every time I try to set CalendarView to focus today (use setDate() to set), it always shows the last day which is available in the Calendar (31 November 2100).
But if i set date to another day it's work fine.
CalendarView cal = new CalendarView(this);
cal.setDate(new Date().getTime(),false,true);
CalendarView cal = new CalendarView(this);
cal.setDate(System.currentTimeMillis(),false,true);
or
cal.setDate(Calendar.getInstance().getTimeInMillis(),false,true);
This is waste of time + headache thing ,I really wonder why there are no one here answer this topic (3years ago!) /or why there is no any top search result in Google to answer this simple problem.
It's too sad that I can't never explain my rage with my bad English skill,
So I will just write it here for the other that will face this issue.
To convert DateTime of C# for Calendar View -> You must subtract tick count of this date 1/1/1970
public static long DatetimeToLong(DateTime dt) {
return (long)( dt - new DateTime(1970, 1, 1)).TotalMilliseconds ;
//(dt - (new DateTime(1970, 1, 1) ) );
}
Calendar_View.SetDate( util.DatetimeToLong(DateTime.Now.Date.AddDays(20) ) ,false ,true);
p.s. Conversion from milliseconds to DateTime format
Related
I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.
I know the Android CalendarView is among the buggiest piece of software in human history, but I must use it so came here asking.
I need to open a CalendarView with:
minimum date set to today;
selected date set to today.
This is how I do it:
int day = 8;
int month = 2;
int year = 2015;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
CalendarView calendarView = (CalendarView) findViewById(R.id.calendarView);
calendarView.setMinDate(calendar.getTimeInMillis()-2000);
calendarView.setDate(calendar.getTimeInMillis(), true, false);
fixIncredibleBugOfCalendarView(calendarView, calendar);
calendarView.setOnDateChangeListener(this);
When I run the previous code, the CalendarView:
shows the 9th of March as the first selectable day, instead of the 8th (DAY_OF_MONTH starts from 1);
shows the 15th of March as the selected date;
So I have geniously decided to include the two lines marked with *:
int day = 8;
int month = 2;
int year = 2015;
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
CalendarView calendarView = (CalendarView) findViewById(R.id.calendarView);
calendar.add(Calendar.DAY_OF_MONTH, -1); // * - subtract one day, i.e. March 7
calendarView.setMinDate(calendar.getTimeInMillis());
calendar.add(Calendar.DAY_OF_MONTH, 1); // * add one day, back to 8
calendarView.setDate(calendar.getTimeInMillis(), true, false);
fixIncredibleBugOfCalendarView(calendarView, calendar);
calendarView.setOnDateChangeListener(this);
In the first line I remove one day, in the second I add one.
With these two more lines, my CalendarView shows:
the 7th of March, as the first selectable date;
the 15th of March, as the selected date.
The method fixIncredibleBugOfCalendarView(...) should fix something (I found it on SO):
private void fixIncredibleBugOfCalendarView(CalendarView cal, Calendar date) {
// Workaround for CalendarView bug relating to setMinDate():
// https://code.google.com/p/android/issues/detail?id=42750
// Set then reset the date on the calendar so that it properly
// shows today's date. The choice of 24 months is arbitrary.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
date.add(Calendar.MONTH, 24);
cal.setDate(date.getTimeInMillis(), false, true);
date.add(Calendar.MONTH, -24);
cal.setDate(date.getTimeInMillis(), false, true);
}
}
This should not be so hard and I do not think it's a bug: it is more likely that it's my fault. Two questions: Could you please be so kind to tell me how to:
tell CalendarView the minimum date it should display?
have CalendarView showing as selected what I decide is the selected date?
Cheers
This is late, probably you have already solved the thing . But Here is my code to solve it
android.icu.util.Calendar c = android.icu.util.Calendar.getInstance();
Long min = c.getTime().getTime();
Long max = 2629746000L + c.getTime().getTime();
CalendarView cv = (CalendarView) findViewById(R.id.date_picker);
cv.setMinDate(min);
cv.setMaxDate(max);
You can also CalenderView just needs to have mindate in long format. You can also go for java
Data d = new Date();
d.getTime();
But Somehow it doesnt work because of current TimeZone.
Instead Calender returns a dateObject with respect to Current TimeZone set.
I am using following code to convert timezone (GMT-3) to device local timezone.
int hour=17,minute=0,day=12,month=6,year=2014;
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-3"));
cal.set(year, (month-1), day,hour,minute);
cal.setTimeZone(TimeZone.getDefault());
Log.d("Time", cal.get(Calendar.DATE)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.YEAR)+" , "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+" "+cal.get(Calendar.AM_PM));
My local timezone is GMT+5:30
Expected result is
Time 13/5/2014, 1:30 0
But I am getting the result
12/5/2014 , 13:30 1
Sorry for you, GregorianCalendar is sometimes the hell. Your problem is following:
If you immediately set the timezone after having set the fields for year, month etc. then this mutable calendar class will only shift the timezone retaining the already set fields containing the local time. Those fields for year, month etc. will NOT be recalculated. This behaviour causes a shift on the global timeline represented by cal.getTime(), too.
In order to force the calendar object to recalculate the fields you need to call a getter. Watch out for following code and especially remove the comment marks to see the effect.
int hour = 17, minute = 0, day = 12, month = 6, year = 2014;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
TimeZone tz1 = TimeZone.getTimeZone("GMT-3");
sdf.setTimeZone(tz1);
Calendar cal = new GregorianCalendar(tz1);
cal.set(year, (month - 1), day, hour, minute);
// System.out.println(sdf.format(cal.getTime()));
// System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
TimeZone tz2 = TimeZone.getTimeZone("GMT+0530");
sdf.setTimeZone(tz2);
cal.setTimeZone(tz2);
System.out.println(sdf.format(cal.getTime()));
System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
Output with comment-disabled lines:
2014-06-12T17:00+0530
Hour=17
Output with enabled lines after having removed the comment marks:
2014-06-12T17:00-0300
Hour=17
2014-06-13T01:30+0530
Hour=1
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).
I am quite new to Android development, but the person has written the code is away and i have taken over this job.
There is one thing I would like to find out quickly...(--
The app is picking up the user input of a date (using a date picker) and i need add a validation to check the if the date is valid. The valid dates are 30 days from today.
After searching on the internet for long time, i've found a code i might can use:
Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse(today);
if(today.before(predefined)) {
...
}
But I am not sure how to add 30 days?
If you could tell me, that would be much appreciated.
Thanks in advance.
Edit Here is the Source code I've tried.
Calendar today = Calendar.getInstance();
today.add(Calendar.DAY_OF_MONTH,30);
if(calStartDate.compareTo(today)<0) {
Toast.makeText(GetClient.this,"It's before valid date!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(GetClient.this,"It's a valid date!",Toast.LENGTH_SHORT).show();
}
You want the Calendar class. You can create one and set it to current time/date, and create another and set roll it forward 30 days. Then call compareTo() on one passing in the other.
Implement this logic in ur OnDateSetListener:::
class DateListner implements OnDateSetListener
{
#Override
public void onDateSet ( DatePicker view , int year , int monthOfYear ,
int dayOfMonth )
{
Date inputDate = new Date(year, monthOfYear, dayOfMonth);
Long inputTime = inputDate.getTime();
Calendar calendar=Calendar.getInstance();
Date validDate = new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), (calendar.get(Calendar.DAY_OF_MONTH)+30));
Long validTime = validDate.getTime();
if(validTime>inputTime){
Log.e("result", "valid");
}
else
Log.e("result", "invalid");
}
}
Cheers......!!!!