如何通过'java.sql.date'获取当前系统月份?

时间:2012-07-19 14:25:30

标签: java date monthcalendar

我希望将当前月份作为字符串从系统中获取,并使用java.sql.Date对象。

我已尝试过以下代码,但Eclipse已触发getMonth()

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

为什么要通过?

3 个答案:

答案 0 :(得分:9)

该方法是在Eclipse中进行的,因为不推荐使用方法getMonth()。 此外,如果您希望将其作为String,则可以使用类SimpleDateFormat将日期转换为String。

例如:

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

答案 1 :(得分:2)

不推荐使用Date Object的getMonth()函数:

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

以下是使用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

答案 2 :(得分:1)

尝试:

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