Take away a single day using Calendar in Java? - java

I have an application that plugs into the Google Fit Api and returns the steps for the last 7 days, the method is below. As the screen shot shows though I wish to add the day to the step count.
I have tried many options to take away one day at a time for the 7 loop but had no luck, it just says the same day. Any help would be great thank you.
private void dumpDataSet(DataSet dataSet) {
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = DateFormat.getTimeInstance();
int i = 0;
for (DataPoint dp : dataSet.getDataPoints()) {
for(Field field : dp.getDataType().getFields()) { //loop 7 times
int test = dp.getValue(field).asInt();
String weekSteps= String.valueOf(test); //get weekday steps one at a time
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Calendar cal = Calendar.getInstance();
String weekday = sdf.format(cal.getTime());
String weekStepsFinal= weekSteps + " steps on " + weekday; //set Textfield to steps and the day
FeedItem item = new FeedItem();
item.setTitle(weekStepsFinal);
feedItemList.add(item);
}
}
}
There are 7 datasets btw.

If by "take away one day at a time" means that you want the days going backwards, then here's how:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
System.out.println("Last 7 days (starting today):");
Calendar cal = Calendar.getInstance(); // Initialized to today/now
for (int i = 0; i < 7; i++) {
System.out.println(" " + sdf.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, -1); // Update to previous day at same time-of-day
}
OUTPUT
Last 7 days (starting today):
Monday
Sunday
Saturday
Friday
Thursday
Wednesday
Tuesday

This will subtract 7 days from the calendar to get you the date 7 days ago:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -7).

To subtract one day use the following code :
int DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Date currentDate = new Date();
long previousDay = currentDate.getTime()-DAY_IN_MILLIS;
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String day = sdf.format(previousDay);

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);

calendar month and year before

I have to put a date one week before and then 1 month before. If i try with the days one week before is working but if the day es 5 and it has to change the month is not working, it changes me the year instead. About the month it changes me the year
tring addUrl = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
// surround below line with try catch block as below code throws checked
// exception
Date endDate = sdf.parse(request.getParameter(field.getId()));
Calendar cal = DateToCalendar(endDate);
cal.setTime(endDate);
SimpleDateFormat formatToSend = new SimpleDateFormat("yyy-mm-dd");
case "day":
cal.add(Calendar.DATE, -1);
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
break;
case "week":
cal.add(Calendar.DATE, -6); // number of days to add
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
break;
default:
cal.add(Calendar.MONTH, -1); // number of days to add
addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
}
How i can do that?
Thanks
In your SimpleDateFormat objects, you should use MM for months and not mm, because mm means minutes, not months.
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat formatToSend = new SimpleDateFormat("yyyy-MM-dd");
See the API documentation of java.text.SimpleDateFormat.
Im not sure do i fully understand the question however one potential problem is in your date format
m = Minute in hour
M = Month in year <- maybe the one you want?
See here for more examples.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Add hours and Minutes to a certain time java

I have String initialTime= "10:30:00"
I am converting it into time like so:-
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Time time = new Time(date.getTime());
int initHour = time.getHours()
int initMind = time.getMinutes();
Further I have two values;
int hour, mins;
The hour value can be anything from 0-10;
mins value can be 0,15,30,45.
The user selects a time by selecting hour and mins. As soon as the user selects the values they should get added to the initialTimeand shown in finalTIme
So if:-
hour=0 and mins=15 then finalTIme=10:45:00
hour=0 and mins=35 then finalTIme=11:00:00
hour=0 and mins=45 then finalTIme=11:15:00
I tried doing something like:-
if(hour==0 && mins==0)
{
finalTime = initialTime;
}
else if(hour==0 && mins>0 && mins <30)
{
mins = initMins + mins
}
else if(hour==0 && mins>0 && mins >=30)
{
hours = hours+1;
mins = mins-60;
}
But I did not get the required output. HOw can I do it in a less complicated manner?
You can use java.util.Calendar class:
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hours);
cal.add(Calendar.MINUTE, minutes);
date = cal.getTime();
You might also consider the new Date API from JDK 8.

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);

how to get minimum and maximum date from given month in java

how to get minimum and maximum date from given month in java using java.util.Calendar.
The minimum is always the 1st of this month. The maximum can be determined by adding 1 to month and subtracting 1 from the Calendar day field.
This could be done this way:
c = ... // get calendar for month you're interested in
int numberOfDays = c.getActualMaximum(Calendar.DAY_OF_MONTH)
You could find minimum and maximum value the same way for any of components of the date.
Have you tried the following?
After setting your calendar object to your desired month,
calendar.getActualMaximum(Calendar.DATE);
For the minimum, I suppose it's always the first.
Hope that helps.
Minimum date is always 1
and Maximum date can be calculate as
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
int year = 2010;
int month = Calendar.FEBRUARY;
int date = 1;
int maxDay =0;
calendar.set(year, month, date);
System.out.println("First Day: " + formatter.format(calendar.getTime()));
//Getting Maximum day for Given Month
maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(year, month, maxDay);
System.out.println("Last Day: " + formatter.format(calendar.getTime()));
Hopefully this will helps
I got solution as below,
public void ddl_month_valueChange(ValueChangeEvent event) {
int v_month = Integer.parseInt(event.getNewValue().toString()) - 1;
java.util.Calendar c1 = java.util.Calendar.getInstance();
c1.set(2011, v_month, 1);
Date d_set_att_from = c1.getTime();
cal_att_from_date.setValue(d_set_att_from);
c1.add(java.util.Calendar.MONTH, 1);
c1.add(java.util.Calendar.DATE, -1);
Date d_set_att_to = c1.getTime();
cal_att_to_date.setValue(d_set_att_to); }

Categories