如何在 Java HashMap 中設定日期值?


建立 Calendar 例項和日期物件 -

Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);

現在,建立一個 HashMap 並存儲日期值 -

LinkedHashMap<String, Integer>hashMap = new LinkedHashMap<String, Integer>();
hashMap.put("year", cal.get(Calendar.YEAR));
hashMap.put("month", cal.get(Calendar.MONTH));
hashMap.put("day", cal.get(Calendar.DAY_OF_MONTH));

示例

 即時演示

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
public class Demo {
   public static void main(String[] argv) {
      Calendar cal = Calendar.getInstance();
      Date date = new Date();
      System.out.println("Date = "+date);
      cal.setTime(date);
      LinkedHashMap<String, Integer>hashMap = new LinkedHashMap<String, Integer>();
      hashMap.put("year", cal.get(Calendar.YEAR));
      hashMap.put("month", cal.get(Calendar.MONTH));
      hashMap.put("day", cal.get(Calendar.DAY_OF_MONTH));
      System.out.println("HashMap (Date) = "+hashMap);
      hashMap.put("hour", cal.get(Calendar.HOUR_OF_DAY));
      hashMap.put("minute", cal.get(Calendar.MINUTE));
      hashMap.put("second", cal.get(Calendar.SECOND));
      hashMap.put("millisecond", cal.get(Calendar.MILLISECOND));
      System.out.println("HashMap (DateTime) = "+hashMap);
   }
}

輸出

Date = Fri Apr 19 17:45:24 IST 2019
HashMap (Date) = {year=2019, month=3, day=19}
HashMap (DateTime) = {year=2019, month=3, day=19, hour=17, minute=45, second=24, millisecond=98}

更新於: 2019 年 7 月 30 日

1000+ 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.