calendar month and year before - java

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

Related

Take away a single day using Calendar in 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);

Trying to get number of days in specific month using Calendar object

I'm trying to write a Calendar in java that outputs an html web page with a Calendar inside of a table, but I've run into a problem when trying to get the number of days in a specific month during a specific year.
This is the bit of code I'm using:
//accept input from command prompt in form of MONTH, DAY, YEAR
String date = args[0];
SimpleDateFormat df = new SimpleDateFormat("MMMM dd, yyyy");
Date convertedDate = new Date();
try
{
convertedDate = df.parse(date);
}
catch(Exception e)
{
System.out.print(e);
}
Calendar cal = Calendar.getInstance();
cal.setTime(convertedDate);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
//get number of days in month
int numDays, startMonth;
numDays = cal.getActualMaximum(DAY_OF_MONTH);
and I'm getting an error from that last line that reads:
error: cannot find symbol and it points to the DAY_OF_MONTH variable.
How can I resolve this?
Use Calendar.DAY_OF_MONTH:
numDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
It's a static field on the Calendar class.

2 months on the week

I have one problem with android calendar programming, so
If there are 2 months on one week, android write me name of old month. I want him to write something like (old month-new month).
My Code is as follows
Calendar wek = Calendar.getInstance(Locale.US);
wek.add(Calendar.WEEK_OF_YEAR,r);
SimpleDateFormat gm = new SimpleDateFormat("MMM yyy");
mes.setText(gm.format(wek.getTime()));
The reason it does this is because when looking at a date represented by a week, it only looks at the first day in the week. You'd need to manually check first and last days of the week and, if they are in a different month, then format the date manually. You also need to be careful about the week overlapping the years as well. Something like this:
Calendar wek = Calendar.getInstance(Locale.US);
wek.add(Calendar.WEEK_OF_YEAR,r);
//this will set your calendar onto the first day of the week
int w = wek.get(Calendar.WEEK_OF_YEAR);
int y = wek.get(Calendar.YEAR);
wek.clear();
wek.set(Calendar.YEAR, y);
wek.set(Calendar.WEEK_OF_YEAR, w);
//get the month and year of the first day of the week
int m1 = wek1.get(Calendar.MONTH);
int y1 = wek1.get(Calendar.YEAR);
//get the date for the end of the week and its month and year
Calendar w2 = wek;
w2.add(Calendar.DATE, 6);
int m2 = w2.get(Calendar.MONTH);
int y2 = w2.get(Calendar.YEAR);
if(m1 == m2) {
//if the two months are the same, then just format the date
SimpleDateFormat gm = new SimpleDateFormat("MMM yyyy");
mes.setText(gm.format(wek.getTime()));
}
else if(y1 == y1) {
//different months, same year - format as "MMM - MMM yyyy"
SimpleDateFormat gm = new SimpleDateFormat("MMM");
SimpleDateFormat gy = new SimpleDateFormat("yyyy");
mes.setTextText(gm.format(wek.getTime()) + " - " +
gm.format(w2.getTime()) + " " +
gy.format(wek.getTime()));
}
else {
//Different months and different years - format as "MMM yyyy - MMM yyyy"
SimpleDateFormat gm = new SimpleDateFormat("MMM yyyy");
mes.setTextText(gm.format(wek.getTime()) + " - " +
gm.format(w2.getTime()));
}
And what is the correct month you think? What you do is add r weeks to the exact moment of now. This is specific point in time and is associated with particular millisecond. This millisecond belongs either to one or the other month. And your code returns which month is that.
You should get the index of the first day of week, and the last one and check the month they belong to.
(I am not a native speaker but you could say that a week overlaps two months, more than a week on 2 months.)

Android : date format in a String

I have a problem to sort date because of the format of these dates.
I obtain the date :
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
And I build a String with these values.
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
The problem is that if the month is for example February, mMonth value is 2. So dates with months like October (10) comes before in my list.
What I need is that month and day are formated like MM and dd. But I don't know how to do it in my case.
EDIT :
I solved the problem by using a DateFormat like said above.
I replaced this :
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
By this :
Date date = new Date(mYear - 1900, mMonth, mDay);
dateFacDB = DateFormat.format("yyyy.MM.dd", date).toString();
And it works.
Thanks to all of you for your help :)
here is a simple way to convert Date to String :
SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy");
String strDt = simpleDate.format(dt);
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
String timestamp = simpleDateFormat.format(now);
These might come in handy
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ");
this format is equal to --> "2016-01-01T09:30:00.000000+01:00"
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
this format is equal to --> "2016-06-01T09:30:00+01:00"
here is the example for date format
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
System.out.println("format 1 " + sdf.format(date));
sdf.applyPattern("E MMM dd yyyy");
System.out.println("format 2 " + sdf.format(date));
You need to sort dates, not strings. Also, have you heared about DateFormat? It makes all that appends for you.
If I understand your issue, you create a list of dates and since they're strings, they get arranged in a dictionary-order number-wise, which means you get october before february (10 before 2).
If I were you, I would store my results in a container where I control the insertion point (like an array list) or where I can control the sorting algorithm.

Challenging Java/Groovy Date Manipulation

I have a bunch of dates formatted with the year and week, as follows:
2011-10
The week value is the week of the year(so 1-52). From this week value, I need to output something like the following:
Mar 7
Explicitly, I need the Month that the given week is in, and the date of the first Monday of that week. So in other words it is saying that the 10th week of the year is the week of March 7th.
I am using Groovy. What kind of date manipulation can I do to get this to work?
Here's a groovy solution:
use(groovy.time.TimeCategory) {
def (y, w) = "2011-10".tokenize("-")
w = ((w as int) + 1) as String
def d = Date.parse("yyyy-w", "$y-$w") + 1.day
println d.format("MMM dd")
}
Use a GregorianCalendar (or Joda, if you don't mind a dependency)
String date = "2011-10";
String[] parts = date.split("-");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, Integer.parseInt(parts[0]));
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(parts[1])+1);
DateFormat df = new SimpleDateFormat("MMM d");
System.out.println(df.format(cal.getTime()) + " (" + cal.getTime() + ")");
EDIT: Added +1 to week, since calendar uses zero-based week numbers
Date date = new SimpleDateFormat("yyyy-w", Locale.UK).parse("2011-10");
System.out.println(new SimpleDateFormat("MMM d").format(date));
The first line returns first day of the 10th week in British Locale (March 7th). When Locale is not enforced, the results are dependent on default JVM Locale.
Formats are explained here.
You can use SimpleDateFormat, just like in java. See groovyconsole.appspot.com/script/439001
java.text.DateFormat df = new java.text.SimpleDateFormat('yyyy-w', new Locale('yourlocale'))
Date date = df.parse('2011-10')
To add a week, simply use Date date = df.parse('2011-10')+7
You don't need to set the Locale if your default Locale is using Monday as the first day of week.

Categories