Get all full hours of every day of a year

倖福魔咒の 提交于 2019-12-12 07:27:35

问题


I need to get / print on command line every full hour of every day of a given year, e.g. 2011 but I am struggling to code it in Java.

Has anybody ever coded this issue?


回答1:


This should work:

final DateFormat df = DateFormat.getDateTimeInstance();
final Calendar c = Calendar.getInstance();
c.clear();
for (c.set(2011, Calendar.JANUARY, 1, 0, 0, 0);
     c.get(Calendar.YEAR) == 2011;
     c.add(Calendar.HOUR_OF_DAY, 1))
  System.out.println(df.format(c.getTime()));

Notice, for example, this subtlety in the output:

Oct 30, 2011 12:00:00 AM
Oct 30, 2011 1:00:00 AM
Oct 30, 2011 2:00:00 AM
Oct 30, 2011 2:00:00 AM
Oct 30, 2011 3:00:00 AM



回答2:


you could easily solve this by using the joda-time library:

    org.joda.time.Hours.hoursBetween(
        new org.joda.time.DateMidnight(2012,1,1).toLocalDate(), 
        new org.joda.time.DateMidnight(2013,1,1).toLocalDate()
      ).getHours();



回答3:


Use Calendar, and loop day after day to manage a "String quoted" as you like by parameter needed,

You can put each line day (usually separated by a comma) in a file



来源:https://stackoverflow.com/questions/12052220/get-all-full-hours-of-every-day-of-a-year

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