Question

I want to get the current month from the system as a string and also by using the java.sql.Date object.

I have tried the code below, but getMonth() is strike through by Eclipse:

java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date( date.getMonth() );

Why is it is strike through?

Was it helpful?

Solution

The method is strike through in Eclipse because the method getMonth() is deprecated. Besides if you want it as a String, you can use the class SimpleDateFormat in order to transform the date to String.

For example:

new SimpleDateFormat("MMMM").format(new Date()); // will output 'july'

OTHER TIPS

Date Object's getMonth() function is deprecated:

getMonth() 
    Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH)

Following is the code using Calender Class

    import java.util.Calendar;

    public class GetMonth
    {
      public static void main(String[] args)
      {
      String[] months = {"January", "February",
      "March", "April", "May", "June", "July",
      "August", "September", "October", "November",
      "December"};

      Calendar cal = Calendar.getInstance(); 
      String month = months[cal.get(Calendar.MONTH)];
      System.out.println("Month name: " + month);
      }
    }

Reference

try:

import java.util.Calendar;

public class GetMonth
{
  public static void main(String[] args)
  {
  String[] months = {"January", "February",
  "March", "April", "May", "June", "July",
  "August", "September", "October", "November",
  "December"};

  Calendar cal = Calendar.getInstance(); 
  String month = months[cal.get(Calendar.MONTH)];
  System.out.println("Month name: " + month);
  }
}

source

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top