Get all full hours of every day of a year

前端 未结 3 1762
青春惊慌失措
青春惊慌失措 2021-01-20 23:04

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?

3条回答
  •  庸人自扰
    2021-01-20 23:44

    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
    

提交回复
热议问题