Get date in milliseconds (long) for upcoming Saturday - android

In my app, I want to show the list of appointments that a User has in this week. The arguments to be passed to the API are fromDate and toDate in milliseconds (long). I need to know how can I get the date in milliseconds of the last day of the week (Consider the week starts from Sunday and ends on Saturday).

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week: " + cal.getTime());
System.out.println("... in milliseconds: " + cal.getTimeInMillis());
for the last day of week add 6 there !!

This can be achieved by adding first day of week as Sunday and then add 6 days to it.
// Get current time. You can reset hours/ minutes/ seconds it with default values which you want.
Calendar c = new GregorianCalendar(Locale.getDefault());
// Set first day of week
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
// Add 6 into that to get Saurday
c.add(Calendar.DAY_OF_WEEK, 6);
// Get millisenconds for Saturday
long millies = c.getTimeInMillis();

Please check the below code to get the upcoming saturday in milliseconds.
public class NextSaturdayMain
{
public static void main(String[] args)
{
System.out.println(getSaturday(new Date()));
}
public static long getSaturday(Date today)
{
Calendar cal = Calendar.getInstance();
cal.setTime(today);
int dow = cal.get(Calendar.DAY_OF_WEEK);
while (dow != Calendar.SATURDAY) {
int date = cal.get(Calendar.DATE);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if (date == getMonthLastDate(month, year)) {
if (month == Calendar.DECEMBER) {
month = Calendar.JANUARY;
cal.set(Calendar.YEAR, year + 1);
} else {
month++;
}
cal.set(Calendar.MONTH, month);
date = 1;
} else {
date++;
}
cal.set(Calendar.DATE, date);
dow = cal.get(Calendar.DAY_OF_WEEK);
}
System.out.println(cal.getTime());
return cal.getTimeInMillis();
}
private static int getMonthLastDate(int month, int year)
{
switch (month)
{
case Calendar.JANUARY:
case Calendar.MARCH:
case Calendar.MAY:
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.OCTOBER:
case Calendar.DECEMBER:
return 31;
case Calendar.APRIL:
case Calendar.JUNE:
case Calendar.SEPTEMBER:
case Calendar.NOVEMBER:
return 30;
default: // Calendar.FEBRUARY
return year % 4 == 0 ? 29 : 28;
}
}
}

Related

Android on Gregorian Calendar

Guys I need help i want to display the month and date along with the day of following 7 days in format like
Sat - 22
Sun - 23
Mon - 24
..
Using a loop
what should be my approach within the loop ::
Calendar cal = new GregorianCalendar();
for(i = 0;i<7;i++)
{
int month = cal.get(Calendar.MONTH);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH + i); // Giving error here
day[i] = dayOfMonth + month + "";
}
I am totally a beginner in this field and im confused help me out
Changing:
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH + i);
to:
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH) + i;
Will fix the error.
But what you are trying to do can be better accomplished with:
Calendar cal = Calendar.getInstance();
for(i = 0; i < 7; i++) {
cal.add(Calendar.DAY_OF_MONTH, 1); // Adds a day to the date and takes care
// of adding month when its the last day of the month already
int weekDay = cal.get(Calendar.DAY_OF_WEEK); // Get weekday name like Sunday
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH)
day[i] = weekDay + " - " + dayOfMonth;
}

Issue in getting difference Date

I only need Today and yesterday date and when other date is selected it should give error....I am getting every thing ok but there is small issue
Here is my code:
if (flag == 0) {
if (getday(myCalendar.getTime()) == 1 || getday(myCalendar.getTime()) == 0) {
setvisitdate();
}
Toast.makeText(getApplicationContext(),
"Selected date is not valid...", Toast.LENGTH_SHORT)
.show();
flag = 0;
new DatePickerDialog(FvrActivity.this, date,
myCalendar.get(Calendar.YEAR),
myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
here is method of getday:
private int getday(Date selected_date) {
Calendar selected_cal = Calendar.getInstance();
selected_cal .setTime(selected_date);
Calendar c = Calendar.getInstance();
c.getTime();
long diffInMillisec = c.getTimeInMillis() - selected_cal.getTimeInMillis();
long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec);
return (int) diffInDays;
}
Suppose today's date is 21/11/2016...I just want to select 21 date and 20 and not 22 but here i can select 22 also..Thank you in advance for solving.
Use this logic:
Calendar selected_cal = Calendar.getInstance();
selected_cal.setTime(selected_date);
//For next day
Calendar nextDay = Calendar.getInstance();
nextDay.add(Calendar.DATE, 1);//Adding one day
nextDay.set(Calendar.HOUR_OF_DAY, 0);//Setting calendar for start hour of the day
nextDay.set(Calendar.MINUTE, 0);//Setting calendar for start minute of the day
nextDay.set(Calendar.SECOND, 0);//Setting calendar for start second of the day
//For previous days
Calendar previousDay = Calendar.getInstance();
previousDay.add(Calendar.DATE, -2);//Adding one day
previousDay.set(Calendar.HOUR_OF_DAY, 23);//Setting calendar for start hour of the day
previousDay.set(Calendar.MINUTE, 59);//Setting calendar for start minute of the day
previousDay.set(Calendar.SECOND, 59);//Setting calendar for start second of the day
if(selected_cal.getTimeInMillis()>=nextDay.getTimeInMillis()
|| selected_cal.getTimeInMillis()<previousDay.getTimeInMillis()){
//Show error
}else{
//Do what you want to do
}

How to I get the list of week days for a specific date in android

I'm implementing the material calendar view in android app,the user can select a particular date in the calendar.how do i get the complete list of week days for that particular selected date
for example: if user selects 22 as the date,how do i get the week days in that row from calendar in which 22 is present
Your requirement is unclear. If you want to get the week day for that day, you can use
Calendar.getInstance().set(year, month, day);
int dayOfWeek = Calendar.getInstance().DAY_OF_WEEK;
Ref : https://developer.android.com/reference/java/util/Calendar.html
try this
public String[] getWeekDaySelected(String selectedDateStr) {
Calendar cal = Calendar.getInstance();
try {
Date startDate = sdf.parse(sdf.format(cal.getTime()));
Date endDate = sdf.parse(selectedDateStr);
weekDaysCount = Functions.getWeeksBetween(startDate, endDate);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String[] days = new String[7];
// set the011, 10 - 1, 12);
String[] arr = selectedDateStr.split("-");
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(arr[2]));
cal.set(Calendar.MONTH, (Integer.parseInt(arr[1]) - 1));
cal.set(Calendar.YEAR, Integer.parseInt(arr[0]));
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK, first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
first.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// 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()));
for (int i = 0; i < 7; i++) {
days[i] = format.format(first.getTime());
first.add(Calendar.DAY_OF_MONTH, 1);
}
return days;
}

Calculating date certain period from now

I have a start date (day, month, year) and need the date say 4 weeks from that date. How can I calculate that? I know how to find the difference between two dates using Calendar so I assume I'm not too far from the answer... Thank you!!!
edit:
This is the final code I wound up using. It returns a String whose value is a date span formatted "MM/dd/YYYY - MM/dd/YYYY"
#SuppressLint("SimpleDateFormat")
private String getSessionDate(int position) {
MySession ms = mSessionList.get(position);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(ms.getStartYear(), ms.getStartMonth(), ms.getStartDay());
Date startDate = calendar.getTime();
String durationString = ms.getDurationString(); // Format is "## weeks"
int i = 0;
while (Character.isDigit(durationString.charAt(i))) {
i++;
}
int weeks = Integer.parseInt(durationString.substring(0, i));
calendar.add(Calendar.WEEK_OF_YEAR, weeks);
return (format.format(startDate) + " - " + format.format(calendar.getTime()));
}
You can use Calender instance for that.
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentdate);
calendar.add(Calendar.DAY_OF_YEAR, no_of_days)
Date newDate = calendar.getTime();
You can calculate the date by adding or subtracting the no of days
Example :
Get date after 1 week
calendar.add(Calendar.DAY_OF_YEAR, 7);
Get date before 1 week
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date date=null;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = originalFormat.parse(strDate); // strDate is your date from which you want to get date after 4 weeks
} catch (Exception e) {
e.printStackTrace();
}
long timeFor4week=4*7*24 * 60 * 60 * 1000; /// here 24*60*60*1000 =24 hours i.e 1 day
long timeAfter4week=date.getTime()+timeFor4week;
String finalDateString=originalFormat.format(new Date(timeAfter4week));
So you can get day after 4 weeks.

setting particular date to Date object

I've been trying this from a long time.
I'm having today's date and I want to compare it with specific date.
But when I set particular date like this, it gives me wrong output:
Calendar cal;
SimpleDateFormat dateformatter;
String currentdate;
cal = Calendar.getInstance();
dateformatter = new SimpleDateFormat("yyyy-MM-dd");
//Getting today's date
currentdate = dateformatter.format(cal.getTime());
Log.i(Class_Tag, "current = " + currentdate);
//Setting specific date
Date start = cal.getTime();
cal.set(2012, 06, 20);
Date end = cal.getTime();
Log.i(Class_Tag, "end = " + dateformatter.format(end));
long diff = end.getDate() - start.getDate();
Log.i(Class_Tag, "diff : " + diff);
long diff1 = end.getMonth() - start.getMonth();
Log.i(Class_Tag, "diff mnth : " + diff1);
long diff2 = end.getYear() - start.getYear();
Log.i(Class_Tag, "diff yr : " + diff2);
if (start.compareTo(end) == 0) {
Log.i(Class_Tag, "EQUAL");
} else if (start.compareTo(end) < 0) {
Log.i(Class_Tag, "end b4 start, delete");
} else {
Log.i(Class_Tag, "start b4 end, do nothing");
OUTPUT:
current = 2012-06-20
end = 2012-07-20 ////WHY it is showing month as '7' when I've set it to '6'?
diff : 0
diff mnth : 1 //Because of the wrong month in end date, this comes 1 instead of 0
diff yr : 0
end b4 start, delete //this also is not correct
I've tried several solutions, but no gains.
My only objective is to get whether that particular date has passed today's date or not.
Any help appreciated.
Edit
in the following code snippet,
//Setting specific date
Date start = cal.getTime();
cal.set(2012, 06, 20);
Date end = cal.getTime();
If I set cal.set(2012, 06, 20); to cal.set(2012, 05, 20);, the month diff. comes out to 0.
This implies that month in particular date is getting incremented by '1', but WHY?
Try this;
Calendar cal = Calendar.getInstance();
long dateNowMillis = cal.getTimeInMillis();
cal.set(2013, 1, 23);
long specDate = cal.getTimeInMillis();
if(dateNowMillis > specDate)
{
System.out.println("Passed");
}
else if(dateNowMillis == specDate)
{
System.out.println("Now");
}
else
{
System.out.println("Not passed");
}
FYI,
A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
You can check read more about Date here and more about SimpleDateFormat.
Update:
One more thing about getMonth() => Its deprecated, instead Calendar.get(Calendar.MONTH), check here.

Categories

Resources