This question already has answers here:
Julian day of the year in Java
(9 answers)
Closed 5 years ago.
I want to get the number of day.. i.e.
Jan 1 is day 1
jan 2 is day 2
Feb 1 is day 32 and december 31 is day 365 or 366 depending on leap year or not
i have used all kind of techniques such as date1 - date2 etc...
but nothing seems to work for me cant get the logic right may be.. what i want is count and add the number of the months that has gone past plus the number days of the running month i.e today is 21st Sept 2012 is day number (31(jan)+29(feb)+31(mar)+30(apr)+31(may)+30(june)+31(july)+31(aug)+20(sept)) = 264th day and they will keep adding plus one every time a day go past... thanks
mycode
int year = Calendar.getInstance().get(Calendar.YEAR);
GregorianCalendar gc = new GregorianCalendar();
gc.set(GregorianCalendar.DAY_OF_MONTH, 8);
gc.set(GregorianCalendar.MONTH, GregorianCalendar.JUNE);
gc.set(GregorianCalendar.YEAR, year);
int numberofDaysPassed=gc.get(GregorianCalendar.DAY_OF_YEAR);
numberofDaysPassed is giving me 160, undesired result
Calendar calendar = Calendar.getInstance();
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
Or using Joda-API
DateTime dt = new DateTime();
int dayOfYear = dt.getDayOfYear();
If you need 'th' part, use switch statement
switch (dayOfYear > 20 ? (dayOfYear % 10) : dayOfYear) {
case 1: return dayOfYear + "st";
break;
case 2: return dayOfYear + "nd";
break;
case 3: return dayOfYear + "rd";
break;
default: return dayOfYear + "th";
break;
}
LocalDate
Use the LocalDate class in java.time package built into Java 8 and later.
Get the day-of-year:
int dayOfYear = LocalDate.now().getDayOfYear();
…and set the day-of-year:
LocalDate localDate = LocalDate.now().withDayOfYear( 195 );
Try setting the date on the calendar to the date in the problem, you asked for 21st Sept but you put 8th of June in the code.
Here is the updated code that gives 265 instead:
int year = Calendar.getInstance().get(Calendar.YEAR);
GregorianCalendar gc = new GregorianCalendar();
gc.set(Calendar.DAY_OF_MONTH, 21); // you asked for 21st Sept but put 8
gc.set(Calendar.MONTH, Calendar.SEPTEMBER); // you aksed for 21st Sept but put JUNE
gc.set(Calendar.YEAR, year);
int numberofDaysPassed = gc.get(Calendar.DAY_OF_YEAR);
System.out.println(numberofDaysPassed);
By the way you don't need to set the month, day etc. on Calendar, it defaults to 'now'...
Using Java 8 you can do this:
int n = LocalDate.now().get(ChronoField.DAY_OF_YEAR);
Calendar ca1 = Calendar.getInstance();
int DAY_OF_YEAR=ca1.get(Calendar.DAY_OF_YEAR);
System.out.println("Day of Year :"+DAY_OF_YEAR);
Check the result in your logcat..
DateTime dt = new DateTime();
String dayOfYear = dt.getDayOfYear().toString();
String day = "";
if(dayOfYear.endsWith("1") && !dayOfYear.endsWith("11"))
day = dayOfYear+"st";
else if(dayOfYear.endsWith("2") && !dayOfYear.endsWith("12"))
day = dayOfYear+"nd";
else if(dayOfYear.endsWith("3") && !dayOfYear.endsWith("13"))
day = dayOfYear+"rd";
else
day = dayOfYear+"th";
System.out.println("Day of year :- "+ day);
Related
This question already has answers here:
Strange behaviour with GregorianCalendar
(8 answers)
Closed 4 years ago.
We are using the below code snippet to get number of days for the provided month and year. For 02 and 2011, It returns the no of days as 31 ( which is not the case). for 02 and 2016, it returns the no of days as 29.
Any clues.
package Processes.BSAInvoiceInquiry.ExternalCall.PaymentStatusInquiry;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class PaymentStatusInquiryJavaCode {
protected int year = 0;
protected int month = 0;
protected int days = 0;
public void invoke() throws Exception {
PaymentStatusInquiryJavaCode a = new PaymentStatusInquiryJavaCode();
System.out.println("Year " + year);
System.out.println("Month " + month);
Calendar calObj = new GregorianCalendar();
calObj.set(Calendar.YEAR, year);
calObj.set(Calendar.MONTH, month - 1);
System.out.println("Month " + Calendar.MONTH);
int numDays = calObj.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("No of the days in the month is " + numDays);
days = numDays;
}
}
This is just another unexpected behavior of Calendar, see this, you can fix it by clear after the creation:
Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 1);
System.out.println(calendar.getActualMaximum(calendar.DAY_OF_MONTH)); //28
The use of outdated Calendar should be avoided. In java8, this can be done by:
YearMonth yearMonth = YearMonth.of(2011, 2);
int lengthOfMonth = yearMonth.lengthOfMonth();
System.out.println(lengthOfMonth); //28
To complete user6690200's answer it returns 29 for 2016 because it's the 29th today and 2016 was a leap year and had a 29th of february. 2011 wasn't a leap year so it actually returns the number for the next month(March which has 31 days).
try
// month 1 based
new Calendar.Builder().setDate(year, month-1, 1).build().getActualMaximum(DAY_OF_MONTH)
the problem is none
calObj.set(DAY_OF_MONTH, 1);
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);
I am creating a Calendar instance, and setting the date to July 1, 1997 like so:
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(1997, 6, 1);
What I want to do, is that without using an external library, get the following output from that date (proper calculating of leap years / seconds would be good, but not required) prior to current date (e.g. November 1, 2015 02:45:30):
18 years, 4 months, 0 days, 2 hours, 45 minutes, 30 seconds
I am not quite sure if this is possible at all. I've tried some weird, not very logical calculations, which needed lots of improvements, but couldn't make it work:
int years = currentYear - calendar.get(Calendar.YEAR);
int months = calendar.get(Calendar.MONTH);
if(currentMonth > months) {
years -= 1;
}
UPDATE - Code until now:
Calendar currentDate = Calendar.getInstance();
currentDate.clear();
Calendar birthDate = Calendar.getInstance();
birthDate.clear();
birthDate.set(this.birthYear, this.birthMonth - 1, this.birthDay);
Calendar date = Calendar.getInstance();
date.clear();
date.setTimeInMillis(birthDate.getTimeInMillis() - currentDate.getTimeInMillis());
System.out.println(Integer.toString(date.get(Calendar.YEAR)));
if you are using java 8 then you have LocalDateTime and PlainTimeStamp classes to use
here you find some answers Java 8: Calculate difference between two LocalDateTime
This might help
Calendar startCalendar = Calendar.getInstance();
startCalendar.clear();
startCalendar.set(1997, 6, 1);
Date start = startCalendar.getTime();
Calendar endCalendar = Calendar.getInstance();
// endCalendar.clear();
// endCalendar.set(2015, 10, 1);
Date end = endCalendar.getTime();
long diff = end.getTime() - start.getTime();
long days = TimeUnit.MILLISECONDS.toDays(diff);
long hours = TimeUnit.MILLISECONDS.toHours(diff) % TimeUnit.DAYS.toHours(1);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff) % TimeUnit.HOURS.toMinutes(1);
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff) % TimeUnit.MINUTES.toSeconds(1);
System.out.println(days + " " + hours + " " + minutes + " " + seconds);
from the days we can write the logic to find the number of leap years, months using modulo division
Java 8 has a new Date API you can try that too since you're using Java 8
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);
I'm trying to create a weekly calendar that looks like this: http://dhtmlx.com/docs/products/dhtmlxScheduler/sample_basic.html
How can I calculate every week date? For example, this week is:
Monday - Sunday
7 June, 8 June, 9 June, 10 June, 11 June, 12 June, 13 June
I guess this does what you want:
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 7; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
With the new date and time API in Java 8 you would do:
LocalDate now = LocalDate.now();
// determine country (Locale) specific first day of current week
DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek();
LocalDate startOfCurrentWeek = now.with(TemporalAdjusters.previousOrSame(firstDayOfWeek));
// determine last day of current week
DayOfWeek lastDayOfWeek = firstDayOfWeek.plus(6); // or minus(1)
LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(lastDayOfWeek));
// Print the dates of the current week
LocalDate printDate = startOfCurrentWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy");
for (int i=0; i < 7; i++) {
System.out.println(printDate.format(formatter));
printDate = printDate.plusDays(1);
}
Java.time
Using java.time library built into Java 8:
import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
LocalDate now = LocalDate.now(); # 2015-11-23
LocalDate first = now.with(previousOrSame(DayOfWeek.MONDAY)); # 2015-11-23
LocalDate last = now.with(nextOrSame(DayOfWeek.SUNDAY)); # 2015-11-29
You can iterate over DayOfWeek.values() to get all current week days
DayOfWeek.values(); # Array(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
for (DayOfWeek day: DayOfWeek.values()) {
System.out.print(first.with(nextOrSame(day)));
} # 2015-11-23, 2015-11-24, 2015-11-25, 2015-11-26, 2015-11-27, 2015-11-28, 2015-11-29
First day of this week.
Calendar c = Calendar.getInstance();
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DATE, -1);
}
Simply setting the day of week does not seem to be reliable. Consider the following simple code:
Calendar calendar = Calendar.getInstance(Locale.GERMANY);
calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF%n", calendar);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF%n", calendar);
System.out.printf("First day of week: %d%n", calendar.getFirstDayOfWeek());
The result of running this program is:
Starting day: 2011-09-18
Last monday: 2011-09-19
First day of week: 2
In other words, it stepped forward in time. For a German locale, this is really not the expected answer. Note that the calendar correctly uses Monday as first day of the week (only for computing the week of the year, perhaps).
You can build up on this: The following code prints the first and last dates of each week for 15 weeks from now.
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
for(int i=0; i<15; i++)
{
System.out.print("Start Date : " + c.getTime() + ", ");
c.add(Calendar.DAY_OF_WEEK, 6);
System.out.println("End Date : " + c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
}
If you know which day it is (Friday) and the current date (June 11), you can calculate the other days in this week.
I recommend that you use Joda Time library. Gregorian Calendar class has weekOfWeekyear and dayOfWeek methods.
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(endDate);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
while (startCal.before(endCal)) {
int weekNumber = startCal.get(Calendar.WEEK_OF_YEAR);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date sunday = cal.getTime();
Log.d("sunday", "" + sdf.format(sunday));
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date saturday = cal.getTime();
Log.d("saturday", "" + sdf.format(saturday));
weekNumber = weekNumber + 1;
startCal.set(Calendar.WEEK_OF_YEAR, weekNumber);
}
Yes. Use Joda Time
http://joda-time.sourceforge.net/
The algorithm you're looking for (calculating the day of the week for any given date) is "Zeller's Congruence". Here's a Java implementation:
http://technojeeves.com/joomla/index.php/free/57-zellers-congruence