Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format date for use in a URL as a parameter

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?

like image 659
user1708240 Avatar asked Dec 09 '25 05:12

user1708240


2 Answers

You should consider SimpleDateFormat date and time patterns: link

For example, something like this:

formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

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
like image 37
MouseLearnJava Avatar answered Dec 11 '25 18:12

MouseLearnJava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!