简体   繁体   中英

How to get the current system month by 'java.sql.date'?

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?

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM