MRX
MRX

Reputation: 1651

java date issue in getting month and year

i am getting problem from extracting month and year from data object.

String strdate = "2012-11-07T13:28:23";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// Date date = dateFormat.parse(strdate);
Date date = new Date();
System.out.println(date.getDate());
System.out.println(date.getYear());
System.out.println(date.getMonth());
System.out.println(date);

my output is like

28
112
10
Wed Nov 28 15:37:30 IST 2012

what is wrong here ?

Upvotes: 2

Views: 774

Answers (7)

Basil Bourque
Basil Bourque

Reputation: 338516

tl;dr

YearMonth ym = 
    YearMonth.from(
        LocalDateTime.parse( "2012-11-07T13:28:23" )
    )

int month = ym.getMonthValue();
int year = ym.getYear();

Details

The other Answers are correct especially the Answer by Jon Skeet.

Let me add that you are using troublesome old legacy date-time classes. Avoid them.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

Parsing string

Your input string lacks any info about offset-from-UTC or time zone. So we parse it as a LocalDateTime where the “Local” means any locality, not one particular. As such it represents a rough idea about possible moments but is not an actual point on the timeline.

ISO 8601

The format of the String complies with the ISO 8601 standard. The java.time classes use these standard formats by default when parsing and generating String objects. So no need to define a parsing pattern.

String input = "2012-11-07T13:28:23";
LocalDateTime ldt = LocalDateTime.parse( input );

Get year & month

The resulting object has better methods for the parts you want plus much more.

Getting the year renders an actual year unlike the trouble you had with the old class. For the year 2016, you get 2016.

int year = ldt.getYear();  // 2016

For month, the getter gives you an object from the handy Month enum. Use such objects in your code base rather than a mere integer to benefit from type-safety, guaranteed valid values, and more self-documenting code.

Month month = ldt.getMonth();

But if you must, you can ask for a number, 1-12 (not the crazy 0-11 you saw in the old class).

int monthNumber = month.getValue();

YearMonth

There is a class for representing the year and month without a date, YearMonth. I suggest passing around objects of this class rather than mere integers. Doing so brings type-safety, valid values, and self-documenting code.

YearMonth ym = YearMonth.from( ldt );

Upvotes: 1

Amir Qayyum Khan
Amir Qayyum Khan

Reputation: 473

Fllow this code and you will get exact month,year and date from:

  String strdate = "2012-11-07T13:28:23";
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  Date date = dateFormat.parse(strdate.toString());

  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  System.out.println("month = " + (cal.get(Calendar.MONTH) + 1 ));// add 1 because Month starts from 0 in java
  System.out.println("year = " + cal.get(Calendar.YEAR)) ;
  System.out.println("date = " + cal.get(Calendar.DATE));
  System.out.println(date);

my output is like

month = 11
year = 2012
date = 7
Wed Nov 07 13:28:23 PKT 2012

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

use calendar object instead

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int year=cal.get(Calendar.YEAR);

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html

Upvotes: 1

Dan D.
Dan D.

Reputation: 32391

When you say new Date(), it will create a new Date object holding the current date and time. You are calling methods on the date value that you have just instantiated.

Upvotes: 1

SJuan76
SJuan76

Reputation: 24885

The Year is based in 1900, so you get 1900 + 112 or 2012 as we call it.

The Month is 0-based (January is the 0-month), so you need to add 1.

Anyway, better use a GregorianCalendar built upon that date to retrieve that info (and many more), since those Date methods are deprecated.

myGregorianCalendar.get(GregorianCalendar.MONTH);

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500495

what is wrong here ?

Your compiler should be telling you what's wrong via warnings: you're using deprecated methods on Date, to start with. Don't ignore those warnings.

You should be using Calendar to get day/month/year etc values, as a Calendar has an associated calendar system and time zone, both of which are required in order to get sensible values out.

Next there's the problem that you're just getting the current date and time instead of using strdate and dateFormat:

// Date date = dateFormat.parse(strdate);
Date date = new Date();

new Date() always returns the current date/time as reported by the system.

However, if you're confused by the 112 and the 10, you should read the documentation for the methods you're calling, which explains that getYear() returns a year based on 1900 (so a return value of 112 means the year is 2012), and getMonth() returns a 0-based month (so January=0). Always read the documentation for methods you're calling, especially if you think they're giving you odd results.

Ideally, however, you should use Joda Time instead - it's a far more sensible date/time API than the built-in one.

Upvotes: 4

mbelow
mbelow

Reputation: 1133

Nothing is wrong. date.getMonth() is zero-based (january = 0)

Upvotes: 1

Related Questions