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.
Related
I am currently using a Date Picker, to display/select a date. I am just having trouble with the format. below is how the example constructed it.
new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" ").toString();
I don't want this format so I tried the following but it keeps giving the incorrect year even if the values are correct so I am not sure what I am doing wrong.
SimpleDateFormat dateFormat = new SimpleDateFormat("d MMMM yyyy");
Date date = new Date(year,month,day);
dates.setText(dateFormat.format(date));
for example if the date was 6 November 2015(current date) and I change it to 6 December 2015 it will display 6 December 3915
The following values are being returned year = 2015 month = 11 day = 6
And this Creates 6 December 3915 I don't understand why the year is not displaying properly if I choose 2016 it would be 3916
This behaviour can be expected actually. This is what the documentation says about the Date constructor you are using (emphasis added by me):
public Date(int year, int month, int day)
Deprecated. instead use the constructor Date(long date)
Constructs a Date object initialized with the given year, month, and day.
The result is undefined if a given argument is out of bounds.
Parameters:
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
month - 0 to 11
day - 1 to 31
So you get 3915 because 2015 + 1900 = 3915
I recommend you don't use this constructor. First of all it is marked as deprecated. Most importantly, no person in his right mind would see an argument int year in a method and think "Of course I have to subtract 1900 from the value I pass"
The LocalDate introduced in Java 8 is recommended as a replacement. You would use it like this
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd MMMM yyyy");
LocalDate date = LocalDate.of(2015, Month.NOVEMBER, 6);
dates.setText(dateFormat.format(date));
the format you are using is wrong. try this instead:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM YYYY");
This question already has answers here:
java.util.Date to java.sql.Date conversion gives wrong month
(2 answers)
Closed 8 years ago.
I am using below code,
private static Date date = new Date (2014-1900,11,25);
System.out.println(date);
It is displaying 2014-12-25. I am unable to understand why it is giving me date as 12?
and if i give
private static Date date = new Date (2014-1900,12,25);
it is returning 2015-01-25.
Can anyone help in comprehend this?
Calendar
It accept December month as 11 because month starts from 0 - 11
First you should not use this Constructor, because it is deprecated.
Second: See the documentation of this consturctor:
Parameters:year -
the year minus 1900.month - the month between 0-11.date - the day of
the month between 1-31.See Also:Calendar
month is a null based value, so 0 --> Jan ... 11 --> Dec
from java docs,
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Month's range from 0-11, ie Jan - Dec
Avoid using the depriciated Date() constructor for setting dates, It is recommended to use Calendar class
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
calendar.set(Calendar.DAY_OF_MONTH, 25);
Date date = calendar.getTime();
You can also use the simpleDateFormat for setting/formatting date values:-
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse("25-11-2014");
//fetch date and convert to date type
String DateString = Integer.toString(getDay()) + "/" + Integer.toString(getMonth()) + "/" + Integer.toString(getYear());
DateFormat parser = new SimpleDateFormat("dd/MM/yyyy"); //current format of date
Date date = (Date) parser.parse(DateString); //convert string to date
//calculate next day
Calendar cal = Calendar.getInstance();
cal.setTime(date); //set calendar time to chosen date
cal.add(Calendar.DATE, 1); //add 1 day to calendar date
//set object to next day
parser.format(cal.getTime()); //set format to dd/MM/yyyy
setDay(cal.get(cal.DAY_OF_MONTH));
setMonth(cal.get(cal.MONTH));
setYear(cal.get(cal.YEAR));
I set a date to 23 October 2002. I want to set it to the next day using the above method. It shows 24 September 2002 instead of 24 October 2002. Why is it adding 1 to the day and removing 1 from the month?
The reason is that months are zero based index ie, they start from 0 instead of 1 so January is 0, Feb is 1, march is 2 and .....Decemeber is 11
From the Oracle docs:
A month is represented by an integer from 0 to 11; 0 is January, 1 is
February, and so forth; thus 11 is December.
EDIT:-
Trying to give the reason for why months start with zero.
The tm structure which is defined in time.h has an integer field tm_mon with the range of 0-11, so I guess this has been taken from the C language. One other reason which might sound wierd but can be reason that since we have names of the month but for days(1,2,3...30,31) we dont have any names
How to get month from a date in java :
DateFormat inputDF = new SimpleDateFormat("mm/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
This code return day and year but not month.
output :
0 - 30 - 2011
This is because your format is incorrect: you need "MM/dd/yy" for the month, because "mm" is for minutes:
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
Prints 8 - 30 - 2011 (because months are zero-based; demo)
First, you used mm in your date format, which is "minutes" according to the Javadocs. You set the minutes to 9, not the month. It looks like the month defaults to 0 (January).
Use MM (capital 'M's) to parse the month. Then, you will see 8, because in Calendar months start with 0, not 1. Add 1 to get back the desired 9.
The first month of the year in the Gregorian and Julian calendars is
JANUARY which is 0
// MM is month, mm is minutes
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
and later
int month = cal.get(Calendar.MONTH) + 1; // To shift range from 0-11 to 1-12
If you read the SimpleDateFormat javadoc, you'll notice that mm is for minutes. You need MM for month.
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Otherwise the format doesn't read a month field and assumes a value of 0.
Month format should be MM instead of mm
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Time for someone to provide the modern answer. The other answers were good answers when the question was asked in 2013 and are still correct. Today there is no reason why you should struggle with the old, outdated and simultaneously notoriously troublesome SimpleDateFormat class. java.time, the modern Java date and time API, is so much nicer to work with:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate date1 = LocalDate.parse("9/30/11", inputFormatter);
System.out.println(date1);
This prints
2011-09-30
The LocalDate class represents a date without time-of-day, exactly what you need, it matches your requirement much more precisely than the old classes Date and Calendar.
The format pattern strings used with DateTimeFormatter resemble those from SimpleDateFormat, there are a few differences. You may use uppercase MM to require two-digit month (like 09 for September) or a single M to allow the month to be written with one or two digits. Similarly dd or d for day of month. yy denotes two-digit year and is interpreted with base 2000, that is, from 2000 to 2099 inclusive (wouldn’t work for my birthday).
Link: Oracle tutorial Trail: Date Time explaining how to use java.time.
Try like this using MM instead of mm:-
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
The month printed will be 8 as index starts from 0
or try with:-
int month = cal.get(Calendar.MONTH) + 1;
mmis for minutes, use MM while specifying format.
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);// returns month value index starts from 0
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);