Reputation: 319
I am using an API to get a weather forecast up until a particular date in Java.
The requirement for passing a date as a URL parameter is that it must be in "YYYY-MM-DD'T'HH:MM:SS" format. I get input in this format from the user, then get the current system date, and then loop until the desired date. The problem lies in converting the input date string into the date format, incrementing it by one day, and then converting it back to the string format for URL parameter.
I am using the following code to do this but it is giving me incorrect results:
formatter = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");
Date date1 = formatter.parse(inputtime);
System.out.println(date1);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
c1.add(Calendar.DAY_OF_MONTH, 1); // number of days to add
inputtime = formatter.format(c1.getTime()); // dt is now the new date
System.out.println(c1.getTime());
System.out.println(inputtime);
inputtime
is the input by the user. If I give "2014-04-12T00:00:00" as inputtime
, date1
is then "Sun Dec 29 00:00:00 PKT 2013", c1.getTime()
returns "Mon Dec 30 00:00:00 PKT 2013" and inputtime
becomes then "2014-12-364T00:12:00" according to the above code block.
How can this logic error be corrected?
Upvotes: 3
Views: 12277
Reputation: 338875
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
That format is defined by the ISO 8601 standard. The Joda-Time library follows that standard's formats as a default for both parsing and generating strings. So does the new java.time package in Java 8.
Your string omits a time zone offset. So, you need to know and specify the time zone intended by that string. Perhaps the time zone is UTC meaning a time zone offset of zero.
A day is not always 24 hours. If you meant 24 hours rather than 1 day, call the method plusHours( 24 )
.
Here is example code in Joda-Time 2.3.
String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.UTC;
DateTime dateTime = new DateTime( input, timeZone );
DateTime tomorrow = dateTime.plusDays( 1 );
String outputWithOffset = tomorrow.toString();
String output = ISODateTimeFormat.dateHourMinuteSecond().print( tomorrow );
Upvotes: 1
Reputation: 3197
Have a try to change your date pattern from
new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");
to
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Letter Date or Time Component Presentation Examples y Year Year 1996; 96 M Month in year Month July; Jul; 07 D Day in year Number 189 d Day in month Number 10 h Hour in am/pm (1-12) Number 12 m Minute in hour Number 30 s Second in minute Number 55 S Millisecond Number 978
Upvotes: 2
Reputation:
You should consider SimpleDateFormat date and time patterns: link
For example, something like this:
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Upvotes: 3