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);
}
}
Related
I try to get the correct difference time between the current day and second selected day from the calendar.
I'm using in this case LocalDate and the 3 methods getDays() getMonths() getYears() to get the day and the month also the year:
public int dateDiff(int year,int month,int day) {
final int Day = c.get(Calendar.DAY_OF_MONTH);
final int Month = c.get(Calendar.MONTH);
final int Year = c.get(Calendar.YEAR);
LocalDate localDate1 = LocalDate.of(year,month,day);
LocalDate localDate2 = LocalDate.of(Year,Month,Day);
Period period = Period.between(localDate2,localDate1);
int dayDiff = period.getDays();
return dayDiff;
}
public void onSelectedDayChange(#NonNull CalendarView view, final int year, final int month, final int dayOfMonth) {
textView.setText(""+dateDiff(year, month, day));
}
But each time when I test the code I got in the textView "0"
I try to see the value of the variable "period" and I got (P2M8D 'this result got in my example') that's mean the variable period count the difference between the days and the problem in the methods.
How can I solve this problem?
The problem in this project are in the name of variables, I'm using the same name of current time and the selected time I just change the first letter with capital one but this make problem.
That's why every time when i run the project i got 0
I change the program like that:
public int dateDiff(int year,int month,int day) {
final int dayOfToday = c.get(Calendar.DAY_OF_MONTH);
final int monthOfToday = c.get(Calendar.MONTH);
final int yearOfToday = c.get(Calendar.YEAR);
LocalDate localDate1 = LocalDate.of(year,month,day);
LocalDate localDate2 = LocalDate.of(Year,Month,Day);
Period period = Period.between(localDate2,localDate1);
int dayDiff = period.getDays();
return dayDiff;
}
Here, this should help.
public int dateDiff(int year,int month,int day) {
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,day);
thatDay.set(Calendar.MONTH,month); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, year);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
return days;
}
This question already has answers here:
How can I add business days to the current date in Java?
(14 answers)
Closed 6 years ago.
How can I increment the day with skipping weekends. I mean if day=Friday then day+1=Monday. Please take a look at my increment method which I increment a calendar day and not a Business day
public Date incDay( Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
I need to modify this method for resolve this issue.
Update:
I update my method like this
public Date incDay(Date date){
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
// public final static int FRIDAY = 6;
final int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.FRIDAY) {
cal.add(Calendar.DATE, 3);
}else{
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.getTime());
return cal.getTime();
}
Main():
public static void main(String[] args) throws ParseException {
Date d=incBusiness(new Date(2017, 02, 17));//2017/02/18
}
I got 2017/02/18 instead of 2017/02/20
Calendar class has constants to check the day of the week:
FRIDAY is the 6th day of the week, doing an if-else can resolve the issue...
public static void foo() throws ParseException {
String dateString = "2017/02/17";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");// "2017/02/17";
Date date = df.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
cal.add(Calendar.DATE, 3);
} else {
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.getTime());
}
Gets date instance and add no. of days excluding weekends. Set date to next monday if provided date is weekend.
public Date addDays(Date date, int days){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
//set date to next monday if provided date day is weekend
//use this section according to your need.
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
cal.add(Calendar.DATE,2);
//days-= 2;
}else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
cal.add(Calendar.DATE,1);
//days--;
}
//add days one by one
while(days > 0){
//if current day is friday add 3 days to skip saturday and sunday
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY){
cal.add(Calendar.DATE,3);
//else add one day
}else{
cal.add(Calendar.DATE,1);
}
//decrements day counter
days--;
}
return cal.getTime();
}
How to get all dates in the calendar in current/some month?
for example for this month, like the picture
So the result is ["07-31-2016", "08-01-2016", "08-02-2016" ... "08-31-2016", "09-01-2016", "09-02-2016", "09-03-2016"]
Any ideas?, thanks in advance.
Well, with Calendar and its constants you can achieve this quite easy:
Given month and year get first day of the month and place calendar on monday:
Calendar start = Calendar.getInstance();
start.set(MONTH, month - 1); // month is 0 based on calendar
start.set(YEAR, year);
start.set(DAY_OF_MONTH, 1);
start.getTime(); // to avoid problems getTime make set changes apply
start.set(DAY_OF_WEEK, SUNDAY);
if (start.get(MONTH) <= (month - 1)) // check if sunday is in same month!
start.add(DATE, -7);
Given month and year get last day of month and move calendar to sunday
Calendar end = Calendar.getInstance();
end.set(MONTH, month); // next month
end.set(YEAR, year);
end.set(DAY_OF_MONTH, 1);
end.getTime(); // to avoid problems getTime make set changes apply
end.set(DATE, -1);
end.set(DAY_OF_WEEK, SATURDAY);
if (end.get(MONTH) != month)
end.add(DATE, + 7);
Test it:
public static void main(String[] args) {
int month = 8, year = 2016;
Calendar start = Calendar.getInstance();
start.set(MONTH, month - 1); // month is 0 based on calendar
start.set(YEAR, year);
start.set(DAY_OF_MONTH, 1);
start.getTime();
start.set(DAY_OF_WEEK, SUNDAY);
if (start.get(MONTH) <= (month - 1))
start.add(DATE, -7);
System.out.println(printCalendar(start));
Calendar end = Calendar.getInstance();
end.set(MONTH, month); // next month
end.set(YEAR, year);
end.set(DAY_OF_MONTH, 1);
end.getTime();
end.set(DATE, -1);
end.set(DAY_OF_WEEK, SATURDAY);
start.getTime();
if (end.get(MONTH) != month)
end.add(DATE, + 7);
System.out.println(printCalendar(end));
}
Combined with:
import static java.util.Calendar.*;
and
private final static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
private static String printCalendar(Calendar c) {
return df.format(c.getTime());
}
OUTPUT:
2016/07/31
2016/09/03
WITH
int month = 5, year = 2015;
OUTPUT:
2015/04/26
2015/06/06
Now, just iterate over starting Calendar adding +1 to Calendar.DATE in a while loop (in the example I split by weeks to be more clear):
int i = 1;
while (start.before(end)) {
System.out.print(printCalendar(start));
if (i % 7 == 0) { // last day of the week
System.out.println();
i = 1;
} else {
System.out.print(" - ");
i++;
}
start.add(DATE, 1);
}
OUTPUT:
2015/04/26 - 2015/04/27 - 2015/04/28 - 2015/04/29 - 2015/04/30 - 2015/05/01 - 2015/05/02
2015/05/03 - 2015/05/04 - 2015/05/05 - 2015/05/06 - 2015/05/07 - 2015/05/08 - 2015/05/09
2015/05/10 - 2015/05/11 - 2015/05/12 - 2015/05/13 - 2015/05/14 - 2015/05/15 - 2015/05/16
2015/05/17 - 2015/05/18 - 2015/05/19 - 2015/05/20 - 2015/05/21 - 2015/05/22 - 2015/05/23
2015/05/24 - 2015/05/25 - 2015/05/26 - 2015/05/27 - 2015/05/28 - 2015/05/29 - 2015/05/30
2015/05/31 - 2015/06/01 - 2015/06/02 - 2015/06/03 - 2015/06/04 - 2015/06/05 - 2015/06/06
java.time
You can use the nice java.time classes built into Java 8 and later. Both the above solutions work, this is a way to do in Java 8. Can be done with a little more brevity , split it just for understanding.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
public class Clazz {
public static void main(String[] args) throws Exception {
LocalDate today = LocalDate.now();
LocalDate firstDayOfTheMonth = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDayOfTheMonth = today.with(TemporalAdjusters.lastDayOfMonth());
LocalDate squareCalendarMonthDayStart = firstDayOfTheMonth
.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate squareCalendarMonthDayEnd = lastDayOfTheMonth
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY));
List<LocalDate> totalDates = new ArrayList<>();
while (!squareCalendarMonthDayStart.isAfter(squareCalendarMonthDayEnd)) {
totalDates.add(squareCalendarMonthDayStart);
squareCalendarMonthDayStart = squareCalendarMonthDayStart.plusDays(1);
}
totalDates.forEach(System.out::println);
}
}
Get the monday before the 1st of that month:
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(2016, 08, 01);
Calendar start = Calendar.getInstance();
start.setFirstDayOfWeek(Calendar.MONDAY);
start.setWeekDate(2016,c.getWeekYear(), Calendar.MONDAY);
Get the sunday after the last day of that month:
c.set(2016,08,31);
Calendar end = Calendar.getInstance();
end.setFirstDayOfWeek(Calendar.MONDAY);
end.setWeekDate(2016, c.getWeekYear(), Calendar.SUNDAY);
Then print all dates between start and end
Write a common method like this and use it -
fun getAllDateOfCurrentMonth(): List<LocalDate> {
val yearMonth= YearMonth.now()
val firstDayOfTheMonth = yearMonth.atDay(1)
val datesOfThisMonth = mutableListOf<LocalDate>()
for (daysNo in 0 until yearMonth.lengthOfMonth()){
datesOfThisMonth.add(firstDayOfTheMonth.plusDays(daysNo.toLong()))
}
return datesOfThisMonth
}
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
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++;
}