Gowtham Ravichandran
Gowtham Ravichandran

Reputation: 15

Date Class error in java

I have Date today=new Date(); which returns the current date.. but when i try to display date,month,year separately with the help of

DateFormat mmFormat=new SimpleDateFormat("MM"); 
System.out.println(mmFormat.format(today.getMonth()));
DateFormat yyFormat=new SimpleDateFormat("yyyy"); 
System.out.println(yyFormat.format(today.getYear()));

it prints month as 01 and year as 1970

how to resolve this.?

Upvotes: 0

Views: 145

Answers (7)

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

Better in this way

    Date date=new Date(); // your date
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DAY_OF_MONTH);
    System.out.println(year+"\n"+month);

Upvotes: 0

Luis Rivera
Luis Rivera

Reputation: 68

That is because all these methods are deprecated. Use

 Calendar myCalendar = GregorianCalendar.getInstance();
 myCalendar.get(Calendar.MONTH);
 myCalendar.get(Calendar.YEAR);
 myCalendar.get(Calendar.DAY_OF_MONTH);

Upvotes: 0

JHS
JHS

Reputation: 7871

You would need to use Calendar. Have a look at the java docs.

You can do it like this -

Calendar cal = Calendar.getInstance();

System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH)); // month in the Calendar class begins from 0
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));

This would help you to avoid creating multiple DateFormat objects. Also in case you want to use another date instead of today's date the you can just pass the date to the cal.setTime() method.

Upvotes: 0

AllTooSir
AllTooSir

Reputation: 49382

today.getMonth() and today.getYear() returns an int which is interpreted as an UNIX timestamp . The value is 1 and 113 , which corresponds to approximately January 1, 1970, 00:00:01 GMT and January 1, 1970, 00:01:53 GMT represented by this Date object. To get the desired result , you need to pass the Date object :

System.out.println(mmFormat.format(today));

Upvotes: 0

SLaks
SLaks

Reputation: 887489

mmFormat.format(today.getMonth())

You're passing an integer – the month of the date – to a date format method.

The format method interprets that integer as a UNIX timestamp – a number of seconds since 1970.

You need to pass the date itself to the formatter.

Upvotes: 3

Reimeus
Reimeus

Reputation: 159794

Just use the Date today as the input argument

System.out.println(mmFormat.format(today));

and

System.out.println(yyFormat.format(today));

Upvotes: 0

jalynn2
jalynn2

Reputation: 6457

Pass the entire date to SimpleDateFormat. The format string "MM" or "yyyy" will cause it to just extract the part of the date you want.

Upvotes: 0

Related Questions