I am designing a system for bookings and need to represent dates only for the year 2015, in the format "dd, mmm, 2015" (e.g. "05 jan 2015"). Im slightly confused about how to do this, it looks like Date supported something like this but has now been depreciated? I'm also confused by the gregorian calendar classes is GregorianCalender(2015, 01, 05) a representation of a date in 2015 or another object entirely?
java.time.LocalDate
If you're using Java 8 or later, you should use java.time.LocalDate
class.
To parse and format this date, you need to use java.time.format.DateTimeFormatter
class.
Usage example:
LocalDate date = LocalDate.of(2015, Month.JANUARY, 5);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd, MMM, yyyy", Locale.ENGLISH);
System.out.println(formatter.format(date)); // prints "05, Jan, 2015"
date = LocalDate.parse("06, Jan, 2015", formatter);
System.out.println(date.getDayOfMonth()); // prints "6"
If you're using Java 7 or earlier, you should use java.util.Date
class to represent a date, java.util.GregorianCalendar
to create a date object from fields or to retrieve date components and java.text.SimpleDateFormat
to parse and format. Usage example:
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.set(2015, Calendar.JANUARY, 5);
Date date = gregorianCalendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd, MMM, yyyy", Locale.ENGLISH);
System.out.println(simpleDateFormat.format(date)); // prints "05, Jan, 2015"
date = simpleDateFormat.parse("06, Jan, 2015");
gregorianCalendar.setTime(date);
System.out.println(gregorianCalendar.get(Calendar.DAY_OF_MONTH)); // prints "6"
Java 8 Date and Time API provide you lot of flexibility on Date and Time usage. Find more about Java 8 Date and Time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With