What I need to do in my Android project is to find all the previous Tuesdays for the last three months and put them into a String Array. It appears that neither the Calendar Class nor SimpleDateFormat would work for this.
So for example, today is Tuesday, so it would start today and I'd need to return 2013_8_13, and next in the array would be 2013_8_6, then 2013_7_30, and so on. Am I wrong about the Calendar Class or SimpleDateFormat? If so, could you give me an idea as to how it could be done?
EDIT: Updated answer to go back to a certain day instead of back a certain number of days. Also changed String array to ArrayList
ArrayList<String> tuesdayArrayList = new ArrayList<String>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_M_d");
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
Date date = new Date();
Date cutoffDate;
int cutoffYear = 2013;
int cutoffMonth = Calendar.JUNE;
int cutoffDayOfMonth = 25;
cutoffDate = new GregorianCalendar(cutoffYear, cutoffMonth, cutoffDayOfMonth).getTime();
while (day != Calendar.TUESDAY) {
calendar.add(Calendar.DATE, 1);
day = calendar.get(Calendar.DAY_OF_WEEK);
}
int i = 0;
while (date.after(cutoffDate)) {
calendar.add(Calendar.DATE, -7);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
date = new GregorianCalendar(year, month, dayOfMonth).getTime();
tuesdayArrayList.add(dateFormat.format(date));
Log.d("myTag: ", tuesdayArrayList.get(i));
i++;
}
Related
I needed to define start/end dates for a person's given age. This seemed simple:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dateOfBirth);
cal.add(Calendar.YEAR, years);
Date start = cal.getTime();
cal.add(Calendar.YEAR, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
Date end = cal.getTime();
Ah, but then there are those born on Leap Day Feb 29th. If the age is not a multiple of 4 then Calendar will round down to the 28th. In this case, my code above will give a date range ending on Feb 27th, and there'll be a gap.
So, I can easily solve this by checking for this condition, and I can wrap the fix up in some method to avoid duplicating it everywhere. But I'm wondering, is there a better solution I'm not aware of? Something that automatically accounts for this special case for a "day before/after" problem?
Here's my solution:
public static Date getAgeStartEnd(Date d, int age, boolean end) {
if (d == null) return null;
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d);
int baseDay = cal.get(Calendar.DAY_OF_MONTH);
cal.add(Calendar.YEAR, age + (end ? 1 : 0));
int newDay = cal.get(Calendar.DAY_OF_MONTH);
boolean roundedDown = baseDay != newDay;
if (end && !roundedDown)
cal.add(Calendar.DAY_OF_MONTH, -1);
else if (!end && roundedDown)
cal.add(Calendar.DAY_OF_MONTH, 1);
d = cal.getTime();
return d;
}
Date start = getAgeStartEnd(dateOfBirth, years, false);
Date end = getAgeStartEnd(dateOfBirth, years, true);
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 7 years ago.
I used a basic technique to implement a method that finds the date of the next day based on the given parameter in the format YYYY-MM-DD and returns the next day in the same format.
Can you please take a look at the code and tell me if it is inefficient or not? It works perfectly fine, but I would prefer to implement a method with more efficiency and fewer lines of code if possible. Keep in mind that any values of the month or day that are single digits numbers have to be formatted with a 0 in the tens place.
public String nextDate(String date){ //ex: 2016-01-31 -returns-> 2016-02-01
int MMrange = 30;
String result = "";
String daystr = date.substring(8,10);
String monthstr = date.substring(5,7);
int day = Integer.parseInt(daystr);
int month = Integer.parseInt(monthstr);
int year = Integer.parseInt(date.substring(0,4));
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) MMrange = 31;
else if(month==2) MMrange = 28;
if(year%4==0&&month==2) MMrange = 29;
if(day==MMrange){
day =1;
month++;
}else if(month==12&&day==31){
year++;
month = 1;
day = 1;
}else{
day++;
}
result = Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day);
if(month <=9&&day<=9) result = Integer.toString(year)+"-0"+Integer.toString(month)+"-0"+Integer.toString(day);
else if(month <= 9) result = Integer.toString(year)+"-0"+Integer.toString(month)+"-"+Integer.toString(day);
else if(day <= 9) result = Integer.toString(year)+"-"+Integer.toString(month)+"-0"+Integer.toString(day);
return result;
}
Try this...
Updated
// imports...
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public static String getNextdt(String dt) {
try {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
final Date date = format.parse(dt);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(format.format(calendar.getTime()));
return format.format(calendar.getTime());
} catch (Exception e) {
}
}
You should use a java.text.DateFormat for format and a java.util.Calendar for calculation like
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 1);
return df.format(cal.getTime());
A shorter way, provided that you use Java 8 is:
LocalDate localDate = LocalDate.now();
localDate.plusDays(1);
System.out.println(localDate.toString());
Hope this works for you.
I want to get the date and month by using a given number. How can I do that with calendar class easily?
example : 079 is march 19.
You need something like that:
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
localCalendar.set(Calendar.DAY_OF_YEAR, 79);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formatted = sdf.format(localCalendar.getTime());
System.out.println(formatted);
This will output "2015-03-20".
Try this is one :
// Get the year, month, day, hour, minute, second
import java.util.Calendar;
public class GetYMDHMS {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// You cannot use Date class to extract individual Date fields
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); // 0 to 11
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
System.out.printf("Now is %4d/%02d/%02d %02d:%02d:%02d\n", // Pad with zero
year, month+1, day, hour, minute, second);
}
}
I'm new to Java
How do I get the total number of months between two (2) jdatechooser? I've search already about this but the date was set to the code, In my case I want to put the dates via JDateChooser.
I can do this through this code but if the year change I was not able to compute the total number of months I want to do this without using JodaTime.
Here is my code
public void month(){
int TotalMonth;
Calendar toDate;
Calendar fromDate;
int increment;
Date dt1 = date1.getDate(); //datechooser 1
Date dt2 = date2.getDate(); //datechooser 2
fromDate = Calendar.getInstance();
toDate = Calendar.getInstance();
if(dt1.after(dt2))
{
fromDate.setTime(dt2);
toDate.setTime(dt1);
}
else
{
fromDate.setTime(dt1);
toDate.setTime(dt2);
}
increment = 0;
TotalMonth = toDate.get(Calendar.MONTH) - (fromDate.get(Calendar.MONTH + increment));
jLabel2.setText(Integer.toString(age));
}
JodaTime is simpler, however...
You need to loop from the start time to the end, incrementing the MONTH field on each loop while the date remains before the end time...
For example...
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal1 = Calendar.getInstance();
cal1.setTime(sdf.parse("08/03/1972"));
Calendar cal2 = Calendar.getInstance();
cal2.setTime(sdf.parse("08/03/2014"));
// Yes, you can use cal1, but I you might want
// to preserve it for other reasons...
Calendar cal3 = Calendar.getInstance();
cal3.setTime(cal1.getTime());
int months = 0;
while (cal3.before(cal2)) {
cal3.add(Calendar.MONTH, 1);
months++;
}
System.out.println("Months = " + months);
} catch (ParseException exp) {
exp.printStackTrace();
}
Prints out Months = 505.
If you change cal2 to 08/04/1972, it will print Months = 1
I've written this simple method to give me the date of every pay period and it has ceased to work as of January first. I'm really not sure what's wrong here. It doesn't return anything.
public static List<Date> getPayPeriodDatesSinceStartOfYear() {
Calendar cal = new GregorianCalendar();
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, 2);
Calendar currentDate = new GregorianCalendar();
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
int counter = 2;
List<Date> dates = new ArrayList<Date>();
while ((cal.getTime().compareTo((currentDate.getTime())) <= 0)) {
dates.add(cal.getTime());
counter += 2;
cal.set(Calendar.WEEK_OF_YEAR, counter);
}
java.util.Collections.reverse(dates);
if(dates.isEmpty()){
JOptionPane.showMessageDialog(null, "NO DATES, SOMETHING IS WRONG!");
}
return dates;
}
Your while condition is not being met, the way you have it set up cal is greater than currentDate therefore the while loop never happens.
Calendar cal = new GregorianCalendar();
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, 2);
Why are you setting week to 1 and then to 2?
(cal.getTime().compareTo((currentDate.getTime())) <= 0)
See the doc for Date. It has methods like before(Date when) and after(Date when).