- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set Date value in Java HashMap?
Create a Calendar instance and Date object −
Calendar cal = Calendar.getInstance(); Date date = new Date(); cal.setTime(date);
Now, create a HashMap and store Date value −
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));
Example
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); } }
Output
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}
- Related Articles
- Remove value from HashMap in Java
- Java Program to retrieve the set of all values in HashMap
- Retrieve a set of Map.Entry elements from a HashMap in Java
- Java Program to retrieve the set of all keys in HashMap
- HashMap in Java
- How to use null value as key in Java HashMap
- Set Date patterns with SimpleDateFormat in Java
- Java Program to remove key value pair from HashMap?
- Java Program to Update value of HashMap using key
- Get the value associated with a given key in Java HashMap
- Modify the value associated with a given key in Java HashMap
- Clone HashMap in Java
- Initialize HashMap in Java
- Java Program to Get key from HashMap using the value
- Java Program to retrieve the set of all keys and values in HashMap

Advertisements