Reputation: 61
Input date is 2016-01-01
, but why output shows 2016/02/01
?
String df = "2016-01-01";
String enddate="";
SimpleDateFormat DATE_FORMAT_QUERY = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
Calendar cal=Calendar.getInstance();
String[] dateStr=df.split("-");
int year=Integer.parseInt(dateStr[0]);
int month=Integer.parseInt(dateStr[1]);
int day=Integer.parseInt(dateStr[2]);
cal.set(year,month,day,23, 59,59);
System.out.println(cal.getTime());
enddate=DATE_FORMAT_QUERY.format(cal.getTime());
System.out.println(enddate);
Output:
Mon Feb 01 23:59:59 EST 2016 20160201T235959Z
Upvotes: 0
Views: 50
Reputation: 27003
ANSWER TO YOUR QUESTION
Input date is 2016-01-01, but why output shows 2016/02/01?
Because Calendar::month is 0-based.
month
- the value used to set theMONTH
calendar field. Month value is 0-based. e.g., 0 for January.
You should use
int month=Integer.parseInt(dateStr[1] - 1);
CORRECT SOLUTION
NEVER parse manually a String
containing a Date
, better get date with SimpleDateFormat
and use it to set Calendar
time:
SimpleDateFormat dfo = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
cal.setTime(dfo.parse("2016-01-01"));
OUTPUT:
Fri Jan 01 00:00:00 CET 2016
20160101T000000Z
Upvotes: 2