how to add days to java simple date format - java

How should I add 120 days to my current date which I got using simple date format?
I have seen few posts about it but couldn't get it to work,
My code is below:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
//get current date time with Date()
Date date = new Date();
Do I need to use the Calendar library or can I just do it with simple date format?

Basically, you can simple use a Calendar which has the capacity to automatically roll the various fields of a date based on the changes to a single field, for example...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 120);
date = cal.getTime();
Take a closer look at Calendar for more details.
Yes, there is a way to do this using Joda Time, but I could type this example quicker ;)
Update with JodaTime example
The following is an example using JodaTime. You could parse the String value directly using JodaTime, but since you've already done that, I've not bothered...
Date date = ...;
DateTime dt = new DateTime(date);
dt = dt.plusDays(120);
date = dt.toDate();

I would suggest you use Joda DateTime if possible. The advantage is it handles TimeZone very gracefully. Here's how to add days:
DateTime added = dt.plusDays(120);
Reference:
http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#plusDays(int)

Related

java- How to add 7 days to a default date?

I have a current date in Java like below:
String currentDate = CoreUtil.parseDate(new Date());
This returns the date for today in the form 2019-03-26.
I declared another date so that it should automatically add 7 days to the current date like below:
String defaultendDate=CoreUtil.parseDate(new Date()); + 7 days //example
So the defaultEnddate should be 2019-04-03
How would I accomplish this as I don't want to use any simple date formatter?
Also, I would like to store the date as it is in String for reasons and secondly, I only want date, not the time. I am not using Java 8 as well, so I can't really use LocalDate library here.
LocalDate is perfect for this job:
LocalDate.now().plusDays(7);
You can get your string representation with
.format(DateTimeFormatter.ISO_DATE);
If you're not able to use Java 8, then you have a few options:
Use the ThreeTen-Backport, which backports most functionality of the Java 8 JSR-310 API, normally available in the java.time package. See here for details. This package is available in Maven Central.
You can also use Joda Time. The peculiar thing is that these two projects have almost the same layout of their websites.
If you're otherwise not able to use ThreeTen-Backport or Joda Time, you can use this:
Calendar c = Gregorian​Calendar.getInstance();
c.add(Calendar.DATE, 7);
String s = new Simple​Date​Format("yyyy-MM-dd")
.format(c.getTime());
Warning
Many things are wrong with the old Date and Time API, see here. Use this only if you have no other option.
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 7);
Date defaultEndDate = cal.getTime();
Something like
LocalDate.now().plusWeeks(1);
would also do the cause.
Please, bare in mind using Java 8 Date/Time API for any operations with dates and times. as it addresses shortcomings of old Date and Calendar regarding thread safety, code design, time-zone logic and other.
UPDATE:
If you must use old Date/Time API, following code would suffice:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("Adding seven days: " + calendar.getTime());
date = calendar.getTime();
//your code
String currentDate = CoreUtil.parseDate(new Date());
*
String dt = new SimpleDateFormat("yyyy.MM.dd").format(new Date()); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 7); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
System.out.println(dt);
*
Use java.util.Date try this one

Getting original date from java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()) and extracting Month

I am using Calendar.getInstance().getTime() to get current date and time in android, additionally following a response is saw on Stackoverflow I am using java.text.DateFormat.getDateTimeInstance().format() to get the string representation of the date I generated earlier and store it in a table. However how can I convert from the string representation back to the Calendar format it came from, and how can I extract the month from there? Please I have tried SimpleDateFormat and it asks me to place suppress warnings all over the place and brings errors. Please any help or better advice or guidance will be greatly appreciated, thxs.
This should give you an idea about how to work with calendar, how to format and parse a date:
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date currentDate = calendar.getTime();
String formattedDate = sdf.format(currentDate);
Date reParsedDate = sdf.parse(formattedDate);
calendar.setTime(reParsedDate);
int month = calendar.get(Calendar.MONTH);
Nevertheless it would be better to keep your date object in some variable instead of reparsing it from the formatted string!

How to convert a date format to mysql date format?

I have bunch of dates in a format like Jan. 14,2014,Apr. 20,2014,Aug. 14,2014 etc,. which are extracted from a set of PDF documents.
My Problem
I added the above dates to a mysql column with Column Datatype as Date using java (by PreparedStatement).
....
st.SetDate(3,"Jan. 14,2014");
....
I added the datas using ExecuteQuery.
But when program executes an error message returned by MySql stating that the date formats are incompatible with MySql column type) Date..
My Question
How to convert this above mentioned date formats into mysql compatible Date formats ?
By your current posted code:
st.SetDate(3,"Jan. 14,2014");
This does not even compile. You could try getting a new Date object from a String (since this is what you're trying to accomplish), so use a SimpleDateFormat for this:
SimpleDateFormat sdf = new SimpleDateFormat("MMM. dd,yyyy");
Date date = sdf.parse("Jan. 14,2014");
st.setDate(3, new java.sql.Date(date.getTime()));
//rest of your code...
Similar to this, you can parse time or date and time into a java.util.Date using SimpleDateFormat and then convert it to the respective class java.sql.Time and java.sql.Timestamp using date.getTime().
Also note that you can p̶a̶s̶s̶ retrieve a java.util.Date object reference to PreparedStatement#getDate (and getTime and getTimestamp) since java.sql.Date, java.sql.Time and java.sql.Timestamp extend from java.util.Date. For more info, please refer here: Date vs TimeStamp vs calendar?
Assuming the column type supports a Date value, you could use a SimpleDateFormat to parse the String values to a java.util.Date and create a java.sql.Date which can be applied to the setDate method...
SimpleDateFormat sdf = new SimpleDateFormat("MMM. dd,yyyy");
Date date = sdf.parse("Jan. 14,2014");
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
Check it SimpleDateFormat for more details
One possible solution is to use the String datatype instead of date in your table.
Use SimpleDateFormat to get the string representation of the date to a Date Object.
This date object can then be used to feed the set date method of the prepared statement.
SimpleDateFormat sdf = new SimpleDateFormat(....)
java.util.Date date = sdf.parse(....);
preparedStmt.setDate(...., date);
first convert the java.util.Date to java.sql.Date then try to set the Java.sql.Date
you can use this logic to convert
If your date is String then first convert it into Java.util.Date type either by using the SimpleDateFormat or DateFormat
If u want to use a DateFormat you can use it also:
But this changes the expected date format depending on the locale settings of the machine it's running on.
If you have a specific date format, you can use SimpleDateFormat:
Date d = new SimpleDateFormat("MMM. dd,yyyy").parse("Jan. 14,2014");
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
I don't really think this all java stuff is necessary. You can simply use this very easy sql process to insert date: NOW() in mysql query like INSERT INTO table_name(c1,c2,datecolumn) VALUES('value1','value2',NOW()); It is much simplier I think :D

TimeZone issue in Java XMLGregorianCalendar

I hope this is not a repeat.
I checked other searches here and all of them seem to talk about "displaying" the date in the right TimeZone format using SimpleDateFormat.
However, my problem is I obtain an XMLGregorianCalendar Object which is let us say in "CET".
I have to find out the format from this object and send the current time also in the same TimeZone as the server.
For eg: I need an XMLGregorianCalendar Object that returns me in this format(with Timezone):
2012-09-19T15:23:36.421+02:00
So I just tried this following snippet which seems to only return the time in local Timezone :(
TimeZone utc = TimeZone.getTimeZone("CET");
GregorianCalendar gc = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
df.setTimeZone(utc);
System.out.println(" - Gregorian UTC [" + df.format(gc.getTime()) + "]")
XMLGregorianCalendar currServTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
System.out.println("currServTime is "+currServTime);
You should include the time zone you're interested in in the GregorianCalendar, either by passing it to the constructor or by setting it afterwards. So either of these lines should work for you:
GregorianCalendar gc = new GregorianCalendar(utc);
gc.setTimeZone(utc);

String to Date in a PreparedStatement

I am trying to use setDate() in a PreparedStatement, however the date that I have is in the format of 2008-07-31. The code is:
pstmt.setDate(f++, (Date) DateFormat.getDateInstance(DateFormat.DEFAULT).parse(value.substring(0, 10)));
However, it gives me the error:
Exception in thread "main" java.text.ParseException: Unparseable date: "2008-07-31"
Why is this?
If you have a very specific date, don't ask Java to use a default date format - set it yourself.
For example:
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
Date date = parser.parse(value.substring(0, 10));
You should also potentially set the time zone of the parser... my guess is that UTC is the most appropriate time zone here.
Note that this has nothing to do with prepared statements as such - it's just date parsing.
(As an alternative to using DateFormat and SimpleDateFormat, you could use Joda Time which has a nicer API and thread-safe formatters/parsers. You can ask Joda Time to convert from its own types to Date values. Possibly overkill if you only need it for parsing here, but if you're doing anything else with dates, it's well worth looking into.)
You need make sure the default DateFormat is in yyyy-MM-dd format (usually it's a config in OS), or you can use SimpleDateFormat or java.sql.Date to parse date string.
java.util.Date d;
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
d = sdf.parse ("2008-07-31");
// or
d = java.sql.Date.valueOf ("2008-07-31");
or, you could just set parameter as String, if the underlying database driver support the VARCHAR/CHAR to DATE conversion.
DateFormat.DEFAULT points to MEDIUM format and MEDIUM format looks like Jan 12, 1952. So, you may have create a SimpleDateFormat object with the format you are using.
I think there is mismatch in the format of the date that you are providing as input and the format in which you have specified while formatting which is default in your case.
SimpleDateFormat parser = new SimpleDateFormay("yyyy-MM-dd");
Try using the same format for both the dates.
First convert String to Date and then set that to PreparedStatement. Check with below code.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date convertedDate = dateFormat.parse(dateString);
I'd use
pstmt.setDate(f++,
new java.sql.Date(
new SimpleDateFormat("yyyy-MM-dd")
.parse(value.substring(0, 10))
.getTime()
)
);

Categories