Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,894 questions

51,825 answers

573 users

How to get the number of the day from the beginning of the year to a given date in Java

2 Answers

0 votes
public class MyClass {
    private static boolean IsLeapYear(int year) {
	    return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    }
    
    private static int GetDayOfYear(int year, int month, int day) {
    	short[] days = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    
    	if (IsLeapYear(year) && month > 2) {
    		return days[month - 1] + day + 1;
    	}
    
    	return days[month - 1] + day;
    }
    
    public static void main(String args[]) {
      	int dayOfYear = GetDayOfYear(2023, 5, 15);

	    System.out.print(dayOfYear);
    }
}






  
/*
run:
  
135
  
*/

 



answered May 15, 2023 by avibootz
edited Dec 13, 2025 by avibootz
0 votes
import java.util.concurrent.TimeUnit;
import java.util.Calendar;
import java.util.Date;

public class MyClass {
    public static void main(String args[]) {
        int year = 2023;
        
        // days elapsed since Jan 1
        Calendar cal1 = Calendar.getInstance();
        cal1.set(year, Calendar.JANUARY, 1, 0, 0, 0);
        cal1.set(Calendar.MILLISECOND, 0);
        Date beginningOfTheYear = cal1.getTime();

        Calendar cal2 = Calendar.getInstance();
        cal2.set(year, Calendar.MAY, 15, 0, 0, 0);
        cal2.set(Calendar.MILLISECOND, 0);
        Date userDate = cal2.getTime();

        long dateBeforeInMs = beginningOfTheYear.getTime();
        long dateAfterInMs = userDate.getTime();

        long timeDiff = Math.abs(dateAfterInMs - dateBeforeInMs);
        long dayOfYear = TimeUnit.DAYS.convert(timeDiff, TimeUnit.MILLISECONDS);

        System.out.println(dayOfYear);
    }
}

 
 
/*
run:

134
 
*/

 



answered May 17, 2023 by avibootz
edited Dec 13, 2025 by avibootz

Related questions

...