Date Class error in java - 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.?

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.

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.

Just use the Date today as the input argument
System.out.println(mmFormat.format(today));
and
System.out.println(yyFormat.format(today));

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));

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.

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);

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);

Related

get Year from java.util.Date

I have a date column in a Cassandra column family. When I retrieve data from this CF using datastax java API, this date object can be taken as a java.util.Date object.
It has a getYear() method but it is deprecated. The corresponding javadoc says:
As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
How can I get the year, month, day attributes from this date object properly?
Could you try like tihs;
// create a calendar
Calendar cal = Calendar.getInstance();
cal.setTime(datetime); //use java.util.Date object as arguement
// get the value of all the calendar date fields.
System.out.println("Calendar's Year: " + cal.get(Calendar.YEAR));
System.out.println("Calendar's Month: " + cal.get(Calendar.MONTH));
System.out.println("Calendar's Day: " + cal.get(Calendar.DATE));
As mentioned in javadocs;
#Deprecated public int getYear() Deprecated. As of JDK version 1.1,
replaced by Calendar.get(Calendar.YEAR) - 1900. Returns a value that
is the result of subtracting 1900 from the year that contains or
begins with the instant in time represented by this Date object, as
interpreted in the local time zone. Returns: the year represented by
this date, minus 1900.
A good option is to use date format as follows:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy");
Date date = sdf1.parse(datetime);
String year = sdf2.format(date);
use LocalDate object in java8
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
To retrieve the date & time fields you can use this code:
DateFormat.getDateTimeInstance().getCalendar().get(DateFormat.MONTH_FIELD)
Just replace MONTH_FIELD with one somehting else like "DAY_OF_WEEK_FIELD" to retrieve the day of the week (I think '1' stands for monday) or "MINUTE_FIELD" for the current minute, etc. :)

Given a java.util.Date object, return start Date of the week

I've a requirement wherein I cannot use JodaDate/Time. I need to use java.util.Date and need a function which returns start Date of the week.
Signature of function:
public java.util.Date getWeekStart(java.util.Date date)
I can assume that the week starts on Sunday. I've done enough research but all solutions are on JodaDate. Can I do this with java.util.Date alone?
Try following code:
public static Date getWeekStart(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date firstDate = c.getTime();
return firstDate;
}
Input for current date would result in following output:
output :
Sun Oct 26 11:46:26 IST 2014
The dig over here is to use Calender for more on it visit this link.
You can use calander class for this, it is easy and more flexible. check below function. may it will help you.
public Date getFirstDayOfWeek(Date date){
Calendar cal=Calendar.getInstance();
cal.setTime(date);
// cal.setFirstDayOfWeek(1); //No need to set , if it is as per local, 1 for sunday and so on.
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
return cal.getTime();
}
It will return first day of the week.

Error getting month while using Calendar object

I'm using Calendar API to manipulate date. Here is snippet of code i'm trying.
Date date=new SimpleDateFormat("dd/mm/yyyy").parse("05/10/2013");
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int month=cal.get(Calendar.MONTH);
Here i should get month as 9(Oct) but its returning 0(Jan).Even if I change date it still returns 0(Jan).
Why this is happening? Please help me.
use MM instead of mm small m gives Minute in hour and to get Month use capital M
Date date=new SimpleDateFormat("dd/MM/yyyy").parse("05/10/2013");
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int month=cal.get(Calendar.MONTH);
System.out.println("" + month);
Output:
9
Java Docs
sue MM instead of mm in the given date format. M specifies month while m specifies minute according to java doc.
Date date=new SimpleDateFormat("dd/MM/yyyy").parse("05/10/2013")
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int month=cal.get(Calendar.MONTH); // add +1 for correct month(10) otherwise it will be 9

Converting Date to Calendar issues

Today is 2013-02-25, but why this code returns 2013-03-25?
String currentDate = new SimpleDateFormat("yyyy MM dd hh mm ss").format(new java.util.Date());
System.out.println("current Date "+currentDate);
StringTokenizer token = new StringTokenizer(currentDate);
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()),
Integer.parseInt(token.nextToken()));
String calenderDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cal.getTime());
System.out.println("calender date "+calenderDate);
cal.add(Calendar.MONTH, -1); // set to one month ago
String pastDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cal.getTime());
System.out.println("past Date "+pastDate);
out put
current Date 2013 02 25 04 56 26
calender date 2013-03-25 04:56:26
past Date 2013-02-25 04:56:26
Subtract one to the month. So it works the API. I.e.:
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
In the JDK, month values start with 0. So 2 = March.
From the Calendar#set docs:
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
Calendar months start at 0, see JavaDoc:
#param month the value used to set the MONTH calendar field.
* Month value is 0-based. e.g., 0 for January.
This is a royal PITA and most Java developers lost some time on that one, it certainly violates the principle of least surprise. Be very careful when using the Calendar class... There are alternatives like Joda time.

How to forcefully cast a string(generated by formating some date) into Date?

I have a string (Jan12) (generated by applying some operations on current date {20-jan-2012}) Now i want to convert back this string into Date format . Also the value should be same i.e the new Date object should have value jan12 and not (20-jan-2012) . Pls help . I have tried doing
java.sql.Date.valueOf("Jan12") [this throws IllegalArgumentException]
and also
new SimpleDateFormat("MMMyy").parse("Jan12") [By this Date gets converted to 20-jan-2012]
Output required : A Date Object having value Jan12 (12 is the year)
My Code : new java.text.SimpleDateFormat("MMMyy").format(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(s)) // It is a string which gives Jan12
Now i really want to convert Mycode into a Date object
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s1 = df.format(now);
System.out.println(s1); // 2012-01-20
java.sql.Date d111=java.sql.Date.valueOf(s1);
System.out.println(d111); // 2012-01-20
DateFormat df1 = new SimpleDateFormat("MMMyy");
String s2 = df1.format(d111);
System.out.println(s2); //Jan12
Now i want s2 to be converted in Date object
#Aditya,
If you use the Str2 which gives "Jan12", there is no date part in that string and therefore if you convert it to a date object, it will get "Jan" as month, 12 as year but it cant find "day" in that String.
if you use below code
try
{
Date d2 = df1.parse(s2); //here s2 is your string which gives "JAN12"
System.out.println(d2);
}
catch(ParseException pe)
{
System.out.println("parse exception..");
}
The output to the above code will be:
Sun Jan 01 00:00:00 IST 2012
notice here that day part is reset to the first day of the month
Therefore, it is not possible to get a complete date object as your original Date, the month and year are preserved, but the day part is lost.
What do you mean "gets converted"? How your Date is displayed is a separate issue. Look into formatting a Date.
So the 12 is day, not a year - you should parse it as such. Aslo, you'll need to tell it what year this is:
System.out.println(new SimpleDateFormat("yyyyMMMdd").parse("2012" + "Jan12"));
Output
Thu Jan 12 00:00:00 EST 2012
Use the SimpleDateFormat class properly, it will do exactly what you want
String str_date="12-Jan-2012";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse(str_date);
Note: the formatter.parse() method throws ParseException, catch it;
If 12 is a year
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMyy").parse("Jan12"));
calendar.set(Calendar.DATE, 1);
Date date = calendar.getTime(); // First Jan 2012
If 12 is a day
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMdd").parse("Jan12"));
calendar.set(Calendar.YEAR, 2012);
Date date = calendar.getTime(); // 12 Jan 2012
I understand that you want to format your Date object into a String representation.
You can use SimpleDateFormat for this, analog to your second example:
Date d = new Date(112, 0, 20); //don't construct a date like this in production code, use a Calendar instance instead
String formattedDate = new SimpleDateFormat("MMMyy").format(d); // -> "Jan12"
Note that your Date object represents a specific point in time, it will always have a day and a time associated with it.
If you want to compare Dates with the resolution of a month, you have to set day and time to neutral values:
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
d = cal.getTime();
Just extend Date and customize it to use your favourite parse & format methods.

Categories

Resources