dealing with Date and Time separately - android

I want to deal with date and time separately in my android app, by saying separately I mean setting the time without affecting the date and vice versa, So, when setting the time only:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR + 1990, Calendar.MONTH, Calendar.DAY_OF_MONTH, hours, minutes, 0);
and it works perfectly, but when setting the Date only:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new_date);
I face a problem of having the time set to 00:00:00, So, I tried to save the time values before and set the date the following way:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new_date);
calendar.set(Calendar.YEAR + 1990, Calendar.MONTH, Calendar.DAY_OF_MONTH, saved_hours, saved_minutes, 0);
But that makes the date saved as it's default value as (Calendar.YEAR||.MONTH||.DAY_OF_MONTH) returns the zero date values of the device which is a date in 1990's despite I'm excuting this command after setting the new Date.
Hint: Methods (mDate.getYear(), mDate.getMonth, .....etc) are deprecated.

To set date and time separately you can use this code
Calendar cal = Calendar.getInstance();
// Note: Months value is MonthNumber-1 (Jan is 0, Feb is 1 and so on).
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,1); // when wanting to set it as 12 Hour system
cal.set(Calendar.HOUR_OF_DAY,13); // when wanting to set it as 24 Hour system
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
// set the year,month and day to something else
//set(int year,int month,int day)
cal.set(1995, 5, 25);
// set(int year,int month,int day,int hourOfDay, int minute,int second)
cal.set(1995, 5, 25, 04, 15, 20);

Related

How to add days and get timestamp in Android?

I want to add days like 30, 60, 90, etc to a date a timestamp like 1642599000000 and want to get the new timestamp. I am using the following code but not working properly. It only works for 30 days only.
Calendar c = Calendar.getInstance();
c.setTimeInMillis(initialTimestamp);
Date date= c.getTime();
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 60); //Adding 60 days to current timestamp
long newTimestamp = cal.getTime().getTime(); //Required this
use c.add(Calendar.DATE, 60); instead DAY_OF_MONTH
DAY_OF_MONTH may be used for fetching number of day in current month (not year, not numer of all days fit into timestamp, which is huge and contains thousands of days)

Calendar not returning the correct time

I want to pick a time from time picker and set an alarm using AlarmManager for that time.
When I use when.getTimeInMillis the value returned is different from the time I´ve set.
For example , if I set the time at 20:40 and I print the value of when.getTime I get 17:12 from next day.
Why is this happening?
Getting time from time picker
MedicationReminder mr=new MedicationReminder(getApplicationContext());
int hour = tp.getCurrentHour();
int min = tp.getCurrentMinute();
Calendar c=Calendar.getInstance();
c.add(Calendar.HOUR, hour);
c.add(Calendar.MINUTE, min);
mr.setReminder(new Medication(name,quant_aux,time),c);
Setting alarm
Intent i = new Intent(mContext, MedicationReceiver.class);
i.putExtra("medName",medication.getName());
i.putExtra("medQuant",medication.getQuantity());
PendingIntent pi=PendingIntent.getBroadcast(mContext,0,i,0);
mAlarmManager.set(AlarmManager.RTC_WAKEUP,when.getTimeInMillis(),pi);
Instead of
Calendar c=Calendar.getInstance();
c.add(Calendar.HOUR, hour);
c.add(Calendar.MINUTE, min);
Try doing
Calendar c=Calendar.getInstance();
c.set(Calendar.HOUR, hour);
c.set(Calendar.MINUTE, min);
If you want to use 24h hour format, then use
c.set(Calendar.HOUR_OF_DAY, hour);
I'm not 100% that's the problem since you didn't include all the code, but I think you're adding 20 hours to the current time instead of setting the calendar to hour 20.
Another note: I believe getCurrentHour() and getCurrentMinute() have been deprecated since API 23, so I suggest you use getHour() and getMinute() instead.

How to show a specific month in android CalendarView?

I want to show a specific month to user using android CalendarView. Please help me to implement this functionality. I wrote following code but it is not working.
CalendarView calendarView = (CalendarView) findViewById(R.id.calendarView);
Calendar calendar1 = Calendar.getInstance();
calendar1.set(2016, 6, 1);
Calendar calendar2 = Calendar.getInstance();
calendar2.set(2016, 6, 30);
calendarView.setMinDate(calendar1.DATE);
calendarView.setMaxDate(calendar2.DATE);
Following output is coming when i am trying to run the app using above code.
Hint: What is the the value of Calendar.DATE? Documentation says 5, and so when you call this method, you are saying "5 milliseconds past Jan 01, 1970."
setMinDate(long minDate)
Sets the minimal date supported by this CalendarView in milliseconds since January 1, 1970 00:00:00 in getDefault() time zone.
Basically, that is a static field, and probably not the value that you want.
Perhaps you want getTimeInMillis() which returns the long for the value that you set the date at?
calendarView.setMinDate(calendar1.getTimeInMillis());
calendarView.setMaxDate(calendar2.getTimeInMillis());
As From my experience i always used Calender.set(Calendar.YEAR, year) method to set year and Calender.set(Calendar.MONTH, month) method to set month and Calender.set(Calendar.DAY,day) method to set day . So i am suggesting you to do same ,
String date = "1/6/2016";
String parts[] = date.split("/");
int day = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
int year = Integer.parseInt(parts[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
long milliTime = calendar.getTimeInMillis();
And now set the selected date in the calendar view by doing
mCalendarView.setDate (milliTime, true, true);

Android converting calendar in one TimeZone to local TimeZone

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

Android Milliseconds as of a time

I have read all of the docs and there doesnt seem to be too much to really explains the date functions, or the lack there of.
I am trying implement the AlarmManger which needs the time in milliseconds (ms) for the trigger. To test I took the current time and added 5 seconds and that was good.
// get a Calendar object with current time
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.SECOND, 5);
If I have a date and time how would I get the ms for that time.
Like "3/2/2011 08:15:00"
How do I turn that into milliseconds?
Use this method.
example:
method call for 3/2/2011 08:15:00
D2MS( 3, 2, 2011, 8, 15, 0);
method
public long D2MS(int month, int day, int year, int hour, int minute, int seconds) {
Calendar c = Calendar.getInstance();
c.set(year, month, day, hour, minute, seconds);
return c.getTimeInMillis();
}
When using AlarmManager you have two choices in setting an alarm - the first is time in ms since device reboot (don't understand that option) or, if you want an 'absolute' time, then you need to provide a UTC time in ms.
I think this should work - I've done something similar in the past...
public long getUtcTimeInMillis(String datetime) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = sdf.parse(datetime);
// getInstance() provides TZ info which can be used to adjust to UTC
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// Get timezone offset then use it to adjust the return value
int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
return cal.getTimeInMillis() + offset;
}
Personally I'd recommend trying to use a non-localised format such as yyyy-MM-dd HH:mm:ss for any date/time string you use if you want to cater for users globally.
The ISO 8601 international standard is yyyy-MM-dd HH:mm:ss.SSSZ but I don't normally go that far.

Categories

Resources