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

本小妞迷上赌 提交于 2019-12-24 16:48:49

问题


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?


回答1:


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);  



回答2:


With Java 8:

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



回答3:


Calendar#get(Calendar.DAY_OF_YEAR);



回答4:


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



回答5:


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();


来源:https://stackoverflow.com/questions/28768869/how-to-know-the-number-of-the-current-day-in-the-current-years-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!