1
 dtNextVisit=cal.getTime();
 out.println(dtNextVisit);

I am not including all code here. This displays "Sun Jan 17 02:53:40 PST 2016" in result because month is January. Now I want to extract and store the month to another variable suppose:

int month=0;

it should display 1.

Hamad
  • 5,096
  • 13
  • 37
  • 65
user3099225
  • 413
  • 1
  • 4
  • 14
  • Use [Calendar.get(int field)](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#get-int-), like `cal.get(Calendar.MONTH)`. – f_puras Jan 14 '16 at 11:10
  • Please search StackOverflow before posting. This topic has already been covered many times. – Basil Bourque Jan 14 '16 at 18:09

3 Answers3

5
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH) + 1;

month will have 1

Kunal_89
  • 309
  • 1
  • 2
  • 10
1

Example:

import java.time.*;
class ABC{
    public static void main(String[] args){
        System.out.println(LocalDate.now().getMonthValue());
    }
}

Edit: I missed up value..

user388229
  • 109
  • 5
  • i know all this .. give me some specific code.. to display the month value. – user3099225 Jan 14 '16 at 11:18
  • doesn't making any sense,, ok... suppose a timestamp ( Sun Jan 17 03:15:05 PST 2016 ) is stored in a variable X. now how extract & display the month value from that ? – user3099225 Jan 14 '16 at 11:28
1

If you are searching for string to date king of conversion, Then java.text.SimpleDateFormat is the one you need to be used. using https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html this link you solve anything. Mark it as answer if correct.

public class Test {    
public int getMonth(String dateText) throws ParseException {

   SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
   Date myday = sdf.parse(dateText);
   System.out.println(myday.getMonth()+1);
   return myday.getMonth() + 1;
}

public static void main(String[] args) throws ParseException {  
  String date = "Sun Jan 17 02:53:40 PST 2016";
  new Test().getMonth(date);
}
}
Sanka
  • 1,294
  • 1
  • 11
  • 20