AndreaNobili
AndreaNobili

Reputation: 42957

How to know the number of the current day in the current years using Java?

I have to calculate in Java what is the number of the current day in the year.

For example if today is the 1 of January the resut should be 1. If it is the 5 of February the result should be 36

How can I automatically do it in Java? Exist some class (such as Calendar) that natively supports this feature?

Upvotes: 1

Views: 190

Answers (5)

Basil Bourque
Basil Bourque

Reputation: 338201

In Joda-Time 2.7:

int dayOYear = DateTime.now().getDayOfYear();

Time zone is crucial in determining a day. The code above uses the JVM's current default time zone. Usually better to specify a time zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
int dayOYear = DateTime.now( zone ).getDayOfYear();

Upvotes: 1

David SN
David SN

Reputation: 3519

int dayOfYear = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);

Upvotes: 2

user987339
user987339

Reputation: 10707

You can use java.util.Calendar class. Be careful that month is zero based. So in your case for the first of January it should be:

    Calendar calendar = new GregorianCalendar(2015, 0, 1);
    int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);  

Upvotes: 2

iceMan33
iceMan33

Reputation: 369

Calendar#get(Calendar.DAY_OF_YEAR);

Upvotes: 2

assylias
assylias

Reputation: 328568

With Java 8:

LocalDate date = LocalDate.of(2015, 2, 5);
int dayNum = date.getDayOfYear();

Upvotes: 5

Related Questions