Java Data Type How to - Store Date value in HashMap








Question

We would like to know how to store Date value in HashMap.

Answer

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
/*from  ww w .j av  a  2 s .c  om*/
public class Main {
  public static void main(String[] argv) {
    System.out.println(getDateMap(new Date()));
  }

  public static LinkedHashMap<String, Integer> getDateMap(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    LinkedHashMap<String, Integer> datemap = new LinkedHashMap<String, Integer>();
    datemap.put("year", cal.get(Calendar.YEAR));
    datemap.put("month", cal.get(Calendar.MONTH));
    datemap.put("day", cal.get(Calendar.DAY_OF_MONTH));
    datemap.put("hour", cal.get(Calendar.HOUR_OF_DAY));
    datemap.put("minute", cal.get(Calendar.MINUTE));
    datemap.put("second", cal.get(Calendar.SECOND));
    datemap.put("millisecond", cal.get(Calendar.MILLISECOND));

    return datemap;

  }
}

The code above generates the following result.