java Calender examples

java Calender examples

The 'Calendar' class is an abstract Java class that represents a calendar and provides methods for manipulating and formatting dates and times. Here are some examples of how to use the 'Calendar' class:

  1. Getting the current date:
import java.util.Calendar;

public class Main {
  public static void main(String[] args) {
    // Gets a Calendar instance with the current date
    Calendar calendar = Calendar.getInstance();

    // Prints the current date
    System.out.println(calendar.getTime());
  }
}
Source:ww‮ttual.w‬uri.com
  1. Setting a specific date:
import java.util.Calendar;

public class Main {
  public static void main(String[] args) {
    // Creates a Calendar instance with the date January 1, 2020
    Calendar calendar = Calendar.getInstance();
    calendar.set(2020, Calendar.JANUARY, 1);

    // Prints the date
    System.out.println(calendar.getTime());  // Prints: Wed Jan 01 00:00:00 BRST 2020
  }
}
  1. Adding or subtracting days, months, or years:
import java.util.Calendar;

public class Main {
  public static void main(String[] args) {
    // Creates a Calendar instance with the current date
    Calendar calendar = Calendar.getInstance();

    // Adds 1 day to the date
	    calendar.add(Calendar.DAY_OF_YEAR,1);
	}
}
Created Time:2017-11-03 00:14:42  Author:lautturi