Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to represent dates in java

Tags:

java

date

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?

like image 392
Massin Avatar asked Apr 07 '15 01:04

Massin


Video Answer


2 Answers

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"
like image 155
vbezhenar Avatar answered Sep 29 '22 00:09

vbezhenar


Java 8 Date and Time API provide you lot of flexibility on Date and Time usage. Find more about Java 8 Date and Time

like image 26
Annamalai Thangaraj Avatar answered Sep 29 '22 02:09

Annamalai Thangaraj