Adding calendar event - java

I want to add an event in android calendar from my application. I have added the event in calendar by using the following code.
Calendar c = Calendar.getInstance();
date2 = formatter.parse(eDate);
c.setTime(date2);
c.add(Calendar.HOUR, 1);
eDate = formatter.format(c.getTime());
date2 = formatter.parse(eDate);
date2 = formatter.parse(eDate);
c.setTime(date2);
eDate = formatter.format(c.getTime());
cal1=Calendar.getInstance();
cal1.setTime(date1);
cal2=Calendar.getInstance();
cal2.setTime(date2);
calEvent.put("dtstart", cal1.getTimeInMillis());
calEvent.put("dtend", cal2.getTimeInMillis());
String timeZone = TimeZone.getDefault().getID();
calEvent.put("eventTimezone", timeZone);
Uri uri = contentResolver.insert(Uri.parse("content://com.android.calendar/events"),
calEvent);
date2 = formatter.parse(eDate);
I need to add one hour to the calendar. So I have added 1 hour to the end date, using the code :
c.add(Calendar.HOUR, 1);
But when I look at in the calendar, it is showing 12 hour event. That means that if a added an event for 10 PM tomorrow, it creates an event from 10 PM tomorrow to 10AM tomorrow.
Can anybody tell me how to add an event that starts at 10 PM tomorrow and ends at 11 PM tomorrow?

You should check your format pattern which you have not shown to us.
More concrete, following code works for me:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd h a");
GregorianCalendar gcal = new GregorianCalendar();
gcal.set(Calendar.MILLISECOND, 0);
gcal.set(2013, Calendar.DECEMBER, 18, 22, 0, 0);
Date date1 = gcal.getTime();
System.out.println(formatter.format(date1)); // Output: 2013-12-18 10 PM
gcal.add(Calendar.HOUR, 1);
Date date2 = gcal.getTime();
System.out.println(formatter.format(date2)); // Output: 2013-12-18 11 PM

You can just add 1 hours (millisecond into your end time),
SomeThing like this
calEvent.put("dtend", calSet.getTimeInMillis() + 60 * 60 * 1000);

Related

Is there a built in function (Java) for an Android app to get the date range of the week of the current date ("today") [duplicate]

I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);

Generate Day start and Day end time between two dates in Java. Day light saving issue

I have to generate days between two two dates. for ex:
1420090495000 -> Jan 1, 2015
1430458495000 -> May 1, 2015
I have to generate timestamps for all days like
Jan 1, 2015 00:00:00 - Jan 1, 2015 23:59:59
Jan 2, 2015 00:00:00 - Jan 2, 2015 23:59:59
Jan 3, 2015 00:00:00 - Jan 3, 2015 23:59:59
so on
I am able to do that. But I am getting some problem with day light saving issue. On march somewhere it is generating like this
Mar 8, 2015 00:00:00 - Mar 9, 2015 00:01:00 Which is wrong and it should be like Mar 8, 2015 00:00:00 - Mar 8, 2015 23:59:59
I found it because of day light saving issue. How to solve this issue ?
My code is:
public static List<String> getDatesRange(long start, long end, String tzOffset) {
//tzOffset is 420. for USA
TimeZone tz = TimeZone.getTimeZone(tzOffset);
List<String> dates=new ArrayList();
Calendar calendar = Calendar.getInstance(tz);
calendar.set(Calendar.DAY_OF_WEEK, 1);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
while (start<end) {
calendar.setTimeInMillis(start);
long startTime = calendar.getTimeInMillis();
int year= calendar.getWeekYear();
long endTime = start + (1 * 24 * 3600 * 1000L);
if(endTime<end) {
endTime-=1000;
System.out.println("Start Date= " + new Date(new Timestamp(start).getTime())+" ("+startTime+"), End Date= "+new Date(new Timestamp(endTime).getTime())+"("+endTime+")");
dates.add(startTime+"-"+endTime);
start= endTime+1000;
}
else{
System.out.println("Start Date= " + new Date(new Timestamp(start).getTime()) + " (" + startTime + "), End Date= " + new Date(new Timestamp(end).getTime()) + "(" + end + ")");
start=end;
dates.add(startTime+"-"+end);
}
}
return dates;
}
There are a couple things I wonder about this:
Why use Longs to define dates?
Why return a list of Strings instead of a list of Dates?
Why take the timezone into consideration at all in a case like this?
Nevertheless, you can achieve this simply using Calendar and SimpleDateFormat, like this:
public static Calendar getDayStart(final long timeInMillis) {
final Calendar cal = Calendar.getInstance();
// end time as a date
cal.setTimeInMillis(timeInMillis);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
public static List<String> getDatesRange(final long start, final long end) {
final Calendar cal = getDayStart(start);
final Date startDate = cal.getTime();
final Calendar calEnd = getDayStart(end);
//adding one day because of the strict comparison in the while below
calEnd.add(Calendar.DAY_OF_YEAR, 1);
final Date endDate = calEnd.getTime();
final SimpleDateFormat formatter = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
final List<String> dates = new ArrayList<String>();
final Date dayEnd;
String currentDay = "";
while(cal.getTime().before(endDate)) {
currentDay = formatter.format(cal.getTime());
currentDay += " - ";
//going to the end of the day
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.add(Calendar.SECOND, -1);
currentDay += formatter.format(cal.getTime());
//going to next day again and continue the loop
cal.add(Calendar.SECOND, 1);
//add what we computed to the list of days
dates.add(currentDay);
}
return dates;
}
The problem is that you want to print dates without the notion of time zones (although the start dates depends on the tzOffset argument). If you use Java 8, the new Java time API has a class specifically designed for that: LocalDate.
So your method can be done by first determining the start and end day based on the timestamp and the time zone then get rid of all time zone considerations. And to print the range you can "cheat" by hardcoding the start/end time in the formatter.
public static List<String> getDatesRange(long start, long end, String tzOffsetMinutes) {
Instant startInstant = Instant.ofEpochMilli(start);
Instant endInstant = Instant.ofEpochMilli(end);
int offsetSeconds = Integer.parseInt(tzOffsetMinutes) * 60;
ZoneOffset offset = ZoneOffset.ofTotalSeconds(offsetSeconds);
LocalDate startDate = OffsetDateTime.ofInstant(startInstant, offset).toLocalDate();
LocalDate endDate = OffsetDateTime.ofInstant(endInstant, offset).toLocalDate();
List<String> dates = new ArrayList<> ();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(
"MMM d, yyyy 00:00:00 - MMM d, yyyy 23:59:59");
for (LocalDate d = startDate; !d.isAfter(endDate); d = d.plusDays(1)) {
dates.add(fmt.format(d));
}
return dates;
}
You can probably do something similar with Calendars.

Calendar DATE trouble

Date toDate = new Date(114, 5, 30);
Calendar calendar = Calendar.getInstance();
Calendar calendarTo = Calendar.getInstance();
calendar.setTime(toDate);
calendarTo.setTime(toDate);
calendarTo.add(Calendar.DATE, 1);
this is how I initialize calendars and I am trying to put NEXT day in calendarTo
but when I getting calendar.Date it is equal to calendarTo.DATE and is equal to 5.. why?
And how I could finally increment this DATE value?
What you are getting is the default value of DATE in Calendar class. Which is 5
public final static int DATE = 5;
But when I print the dates from your code, looks like it is fine.
Date toDate = new Date(114, 5, 30);
Calendar calendar = Calendar.getInstance();
Calendar calendarTo = Calendar.getInstance();
calendar.setTime(toDate);
calendarTo.setTime(toDate);
calendarTo.add(Calendar.DATE, 1);
System.out.println(toDate);//Mon Jun 30 00:00:00 IST 2014
System.out.println(calendarTo.getTime());//Tue Jul 01 00:00:00 IST 2014

To find wednesday between to dates given by the user

I need to find wednesday for the two dates given by the user.
example:
Inputs are:
from date:07-Feb-2013
To date:13-feb-2013
The gap between the from date and To date is 7 days always.
Expected Output:12-feb-2013
public String getAutoDayExpiryDateAndToDate(String instrmentId,String deliveryAutoFromDate)
throws SystemException, FunctionalException,ParseException
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(deliveryAutoFromDate));
Date fromDate=calendar.getTime();
SimpleDateFormat sf1 = new SimpleDateFormat("dd-MMM-yyyy");
String formatedDate = sf1.format(fromDate);
calendar.add(Calendar.WEEK_OF_MONTH, 1);
calendar.add(Calendar.DAY_OF_WEEK,-1);
Date time = calendar.getTime();
SimpleDateFormat sf = new SimpleDateFormat("dd-MMM-yyyy");
String formatedDate1 = sf.format(time);
}
after these i need to find Wednesday which is present between formatedDate and formatedDate1 .how can i do it??
Use the Calendar class. Set it to the first date, and then check if the current day of the week is Wednesday by calling calendar.get(Calendar.DAY_OF_WEEK). Perform this check in a loop, adding a day to the current date during each iteration. This will never take more than seven steps, so you don't need to do anything fancier than that.
this should find the first Wednesday after (or equal) the given date
GregorianCalendar c = new GregorianCalendar(2013, 1, 7);
if (c.get(Calendar.DAY_OF_WEEK) <= Calendar.WEDNESDAY) {
c.add(Calendar.DAY_OF_YEAR, Calendar.WEDNESDAY - c.get(Calendar.DAY_OF_WEEK));
} else {
c.add(Calendar.DAY_OF_YEAR, 11 - c.get(Calendar.DAY_OF_WEEK));
}
System.out.println(c.getTime());
prints
Wed Feb 13 00:00:00 EET 2013
you can test it to see if it gives you what you want

Getting the start and the end date of a week using java calendar class

I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);

Categories