Date class LocalDate in Java

Java core technology Volume 1 (version 10) recommends using classes under the java.time package, such as LocalDate, to p...

Java core technology Volume 1 (version 10) recommends using classes under the java.time package, such as LocalDate, to process dates based on the newer JDK.

import java.time.LocalDate; public static void main(String[] args) { LocalDate datetime; }

Some common localdate APIs

  • static LocalTime now(); constructs the LocalDate object of the current date
  • static LocalTime of(int year, int month, int day); constructs the LocalDate object for a given date
  • int getYear(); returns the year of the current date of the LocalDate object
  • int getMonthValue(); returns the month of the current date of the LocalDate object
  • int getDayOfMonth(); returns the date of the current date of the LocalDate object
  • DayOfWeek getDayOfWeek; get the current day of the week, return as an instance of DayOfWeek class, call getValue to get a number between 1-7
  • LocalDate plusDays(int n); returns the date after the current date + the number of days given the shaping data
  • LocalDate minusDays(int n); generates the date n days after or before the current date

Use LocalDate to build a calendar table for the current date:

/** * Build calendar for current date * @param args */ public static void main(String[] args) { LocalDate date = LocalDate.now(); int month = date.getMonthValue(); int today = date.getDayOfMonth(); //Set date as the first day of the current month date = date.minusDays(today - 1); //Get date what day of the week DayOfWeek weekday = date.getDayOfWeek(); int value = weekday.getValue(); System.out.println("Mon Tue Wed Thu Fri Sat Sun"); for (int i = 1; i < value; i++) { System.out.print("\t"); } while (date.getMonthValue() == month) { System.out.printf("%3d", date.getDayOfMonth()); if (date.getDayOfMonth() == today) { System.out.print("*"); } else { System.out.print(" "); } date = date.plusDays(1); if (date.getDayOfWeek().getValue() == 1) { System.out.println(); } } if (date.getDayOfWeek().getValue() != 1) { System.out.println(); } }

9 February 2020, 13:24 | Views: 7434

Add new comment

For adding a comment, please log in
or create account

0 comments