Skip to main content

APIzation: Replication Package

[Q#1711801][A#1711820] How to create a calendar object in Java

https://stackoverflow.com/q/1711801

I need to turn a Date object into a calendar in Java, and try to access its field value for HOUR_OF_DAY. Does anybody know how to do it?

Answer

https://stackoverflow.com/a/1711820

Use the setTime method:

APIzation

Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
package com.stackoverflow.api;

import java.util.Calendar;
import java.util.Date;

public class Human1711820 {

  public static int getHourOfDay() {
    Date date = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(Calendar.HOUR_OF_DAY);
  }
}

package com.stackoverflow.api;

import java.util.Calendar;
import java.util.Date;

/**
 * How to create a calendar object in Java
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/1711820">https://stackoverflow.com/a/1711820</a>
 */
public class APIzator1711820 {

  public static int createObject() throws Exception {
    Date date = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    return calendar.get(Calendar.HOUR_OF_DAY);
  }
}