int day = Integer.parseInt(request.getParameter("day")); // 25
int month = Integer.parseInt(request.getParameter("month")); // 12
int year = Integer.parseInt(request.getParameter("year")); // 1988
System.out.println(year);
Calendar c = Calendar.getInstance();
c.set(year, month, day, 0, 0);
b.setDob(c.getTime());
System.out.println(b.getDob());
Output is:
1988
Wed Jan 25 00:00:08 IST 1989
I am passing 25 12 1988 but I get 25 Jan 1989. Why?
Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use
c.set(year, month - 1, day, 0, 0);
That's my favorite way prior to Java 8:
Date date = new GregorianCalendar(year, month - 1, day).getTime();
I'd say this is a bit cleaner than:
calendar.set(year, month - 1, day, 0, 0);
java.time
Using java.time framework built into Java 8
int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22
If you need also information about time(hour,minute,second) use some conversion from LocalDate to LocalDateTime
LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
See JavaDoc:
month - the value used to set the MONTH calendar field. Month value is
0-based. e.g., 0 for January.
So, the month you set is the first month of next year.
Make your life easy when working with dates, timestamps and durations. Use HalDateTime from
http://sourceforge.net/projects/haldatetime/?source=directory
For example you can just use it to parse your input like this:
HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate ); // will print in ISO format: 1988-12-25
You can also specify patterns for parsing and printing.
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");
I just want to subtract 1 day from New year date in my current scenario.
But while I subtract I get date: 31-0-2100.
Calendar cal = Calendar.getInstance();
cal.set(2100, 1, 1);
cal.add(Calendar.DATE, -1);
String dateStr = ""+cal.get(Calendar.DATE)+
"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.YEAR);
System.out.println(dateStr);
The actual date should be: 31-12-2099
When you're doing cal.set(2100, 1, 1);, the date you set is actually the first day of February and not January since months are 0 base indexed (0 -> January, ..., 11 -> December).
I would recommend you to use JodaTime which is a far better library to deal with dates and time.
DateTime date = new DateTime(2100, 1, 1, 0, 0, 0);
date = date.minusDays(1);
System.out.println(date.toString("dd-MM-yyyy")); //31-12-2099
Or if you're using java-8, they introduced a brand-new date and time API:
LocalDate date = LocalDate.of(2100, Month.JANUARY, 1);
date = date.minusDays(1);
System.out.println(date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))); //31-12-2099
In java the month 0 is January.
So what you got is correct since you're substracting 1 day from February 1st 2100
Notice that the field MONTH is 0-indexed, so the month '1' is actually February and what you are getting: '31-0'2100' is the last day of January.
Source: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#MONTH
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Implemented using Calendar functionality.
Tested and Executed
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
cal.set(2099, 00, 01);
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
Another solution Formulate the DateTime using the below methods
date.getYear();
date.getDay();
date.getMonth();
Try to pass those arguments into the DateTime.
DateTime date = new DateTime(2100, 1, 1, 0, 0, 0);
date = date.minusDays(1);
System.out.println(date.toString("yyyy-MM-dd"));
Use this instead:
call.add(Calendar.DAY_OF_MONTH, -1)
I have verified that the date is read correctly from a file, but once I use SimpleDateFormat.format with the pattern "dd/MM/yy" it suddenly adds a month. This leads me to believe lenient mode is calculating the wrong value. But I have no idea what would make it add a full month.
Some example dates I read:
16/09/2013
23/09/2013
30/09/2013
07/10/2013
14/10/2013
21/10/2013
The code used to parse the date (it's a wrapper around Calendar I made):
public static SimpleDateTime parseDate(String date)
{
String[] dateParts = date.split("[-\\.:/]");
int day = Integer.parseInt(dateParts[0]);
int month = Integer.parseInt(dateParts[1]);
int year = Integer.parseInt(dateParts[2]);
return new SimpleDateTime(dag, maand, jaar);
}
The constructor used here:
public SimpleDateTime(int day, int month, int year)
{
date = Calendar.getInstance();
date.setLenient(true);
setDay(day);
setMonth(month);
setYear(year);
}
The setters for day, month and year:
public void setYear(int year)
{
date.set(Calendar.YEAR, year);
}
public void setMonth(int month)
{
date.set(Calendar.MONTH, month);
}
public void setDay(int day)
{
date.set(Calendar.DAY_OF_MONTH, day);
}
And the code used to format the date:
public String toString(String pattern)
{
String output = new SimpleDateFormat(pattern, Locale.getDefault()).format(date.getTime());
return output;
}
where the pattern passed is:
"dd/MM/yy"
Intended to print a date as:
16/09/13
23/09/13
Instead I get:
16/10/13
23/10/13
January is 0 in Java; February is 1 and so on.
See Calendar.JANUARY, Calendar.FEBRUARY.
So when you're reading 1 from the file
you think you read JAN but you read FEB.
You should do: date.set(Calendar.MONTH, month-1); to fix this.
Months are indexed from 0 not 1 so 10 is November and 11 will be December.
Calendar.MONTH
From documentation:
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year is JANUARY; the last depends on the number of months in a year.
So if you check JANUARY you see it starts in zero.
Make sure your month is in the interval 0-11. Possibly it is in 1-12.
The reason for this is that the counting starts at 0.
January == 0
February == 1
and so on. See the documentation.
THe problem is that you pass 9 to SimpleDateFormat and since month are indexed from 0 to 11 it will parse month '9' as the 10th month.
You need to subtract 1 from the month :)
Calendar class in Java holds months starting from 0, hence when you set the month as 0, it would consider it as January. SimpleDateFormat provides for a way to correctly display the value as 01.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 0);
System.out.println(new SimpleDateFormat("dd/MM/yy").format(cal.getTime()));
Output:
29/01/14
The workaround for you to align you file that Calendar can work with (since December - or 12 would trickle over to the next year) or modify your logic to pick Constants like:
cal.set(Calendar.MONTH, Calendar.JANUARY);
The answer by peter.petrov is almost correct, except for one major problem. Like your question, it neglects to account for time zone.
For your information, this kind of work is much easier in Joda-Time (or new java.time.* classes in Java 8). Joda-Time is so much cleaner you won't even feel the need to create a wrapper class.
// Specify the time zone for which the incoming date is intended.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Brussels" );
String input = "16/09/2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy").withZone( timeZone );
DateTime dateTime = formatter.parseDateTime( input );
String output = formatter.print( dateTime );
Dump to console…
System.out.println( "dateTime: " + dateTime );
System.out.println( "output: " + output );
System.out.println( "millis since Unix epoch: " + dateTime.getMillis() );
When run…
dateTime: 2013-09-16T00:00:00.000+02:00
output: 16/09/2013
millis since Unix epoch: 1379282400000
I manage some dates in my own date classes. I want to create a method like this in my date:
int getWeekdayIndex()
right now it lookes something like this:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(year, month+1, day); // data of this date
int weekdayIndex = cal.get(Calendar.DAY_OF_WEEK);
return weekdayIndex;
I know DAY_OF_WEEK returns 1(Sunday) to 7(Saturday), but if I test this method with
2014-01-06 I get index 5 (suppost to be 2)
2014-01-07 I get index 6 (suppost to be 3)
(I live in Berlin UTC+01:00 - if it matters)
You should use:
cal.set(year, month-1, day); // data of this date
Do note the month-1 part instead of month+1.
Assuming that month's value is:
1 for Jan
2 for Feb
3 for Mar
...
What is month in your scenario? If it's 0 for "January", you are adding 1 when calling the set method. But months in Java are zero-based, so you're setting "February", and February 6th, 2014 is a Thursday (5), and February 7th, 2014 is a Friday (6).
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.
Try changing
cal.set(year, month+1, day);
to
cal.set(year, month, day);
FYI, Joda-Time 2.3 has convenient methods for such work.
The DateTime class offers a dayOfWeek method. From that you can derive either the localized name of the day, and to your needs, the number. Joda-Time counts days using the international standard ISO 8601, where Monday is 1 and Sunday is 7.
Example code…
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
DateTimeZone berlinTimeZone = DateTimeZone.forID( "Europe/Berlin" );
DateTime dateTime = new DateTime( 2013, DateTimeConstants.DECEMBER, 13, 14, 15, 16, berlinTimeZone );
String dayOfWeekAsText = dateTime.dayOfWeek().getAsText( Locale.GERMANY );
int dayOfWeekAsNumber = dateTime.dayOfWeek().get();
System.out.println( "dayOfWeekAsText: " + dayOfWeekAsText );
System.out.println( "dayOfWeekAsNumber: " + dayOfWeekAsNumber );
When run…
dayOfWeekAsText: Freitag
dayOfWeekAsNumber: 5
Easy to jump to another month.
DateTime previousMonthDateTime = dateTime.minusMonths( 1 );
DateTime nextMonthDateTime = dateTime.plusMonths( 1 );
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