This method can be used to convert a formatted string representation of a date into a Date object.
/** * Parses the date using the given format. * * formattedDate the formatted date string * dateFormat the date format which was used to create the string. * return the date */ public static Date parseDate(String formattedDate, String dateFormat) { Date date = null; SimpleDateFormat ogj = new SimpleDateFormat(dateFormat); try { date = ogj.parse(formattedDate); } catch (ParseException e) { // Do what ever needs to be done with exception. } return date; }
Date currentDate = new Date(); System.out.println(currentDate); // Outputs something like: Fri Dec 30 17:00:00 UTC 2023
Here this Date object contains the current date and time when this object was created.
Calendar newCalendar = Calendar.getInstance(); newCalendar.set(2025, Calendar.OCTOBER, 15); Date someDate = newCalendar.getTime(); System.out.println(someDate); // Outputs something like: Fri Oct 15 00:00:00 UTC 2025
Date objects are best created through a Calendar instance since the use of the data constructors is deprecated and discouraged. To do se we need to get an instance of the Calendar class from the factory method. Then we can set year, month and day of month by using numbers or in case of months constants provided py the Calendar class to improve readability and reduce errors
Calendar differentCalendar = Calendar.getInstance(); differentCalendar.set(2000, Calendar.OCTOBER, 5, 18, 45, 0); Date specialDate = differentCalendar.getTime(); System.out.println(specialDate); // Outputs something like: Fri Oct 05 18:45:00 IST 2000
Along with date, we can also pass time in the order of hour, minutes and seconds.
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions