Date(dateFormat.parse("string date").getTime()) Error - java

i have a string date 2020-01-14 00:00:00.0
when i convert this string date using
new java.sql.Date(dateFormat.parse("2020-01-14 00:00:00.0").getTime())
this will result the date as 0019-07-13
i am not getting how it is converting the string ...
pls help me
thanks

DateFormat.parse() is abstract, and SimpleDateFormat.parse() is +- 120 lines long. Presumably you're using SimpleDateFormat to do your parsing. SimpleDateFormat is initialised using the format specified in your current Locale by default if you do not pass a specific format string to your call to SimpleDateFormat's constructor.
ensure that you initialise dateFormat as follows
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
and your issues should go away.

Related

SimpleDateFormat ignores TimeZone

I have read a bunch of posts on this, but, I am obviously missing something. I have date string, and a time zone. I am trying to instantiate a date object as follows:
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
java.util.Date dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj);
What is printed is:
Sun Oct 06 09:30:00 EDT 2013
What I want is a date object in UTC format. Not one converted to EDT. What am I doing wrong?
Thanks.
This is because a Date object does not store any timezone information. Date basically only stores the number of milliseconds since the epoch (Jan. 1, 1970). By default Date will use the timezone associated with the JVM. In order to preserve timezone information you should continue using the DateFormat object that you've already got.
See DateFormat#format(Date): http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)
The following should give you what you're looking for:
System.out.println(sdf.format(dateObj));
Try below code, you'll see that the date parsed 1st time is different from the one parsed after setting timezone. Actually the date is parsed as expected in right timezone. It s while printing it gives you get the machines's default TZ.
You could have printed the dateObj.toGMTString() to check the same, but that is deprecated.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj.toString());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
dateObj = sdf.parse("2013-10-06 13:30:00");
System.out.println(dateObj.toString());

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

JodaTime: How hours are represented

I am working with JodaTime now and have a question about how to parse String into DateTime.
I have got a date String in the format:
"2013-05-14T11:36:08+0000"
I tried to convert it into JodaTime's DateTime object:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
DateTime dateTime = fmt.parseDateTime("2013-05-14T11:36:08+0000");
It works fine except that if I call
dateTime.getHourOfDay()
It returns me 12 instead of 11.
Surprisingly, if I use the Java's SimpleDateFormat:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = df.parse("2013-05-14T11:36:08+0000");
The date contains exactly the same result, the hour is 12 instead of 11.
I am based in London. I started to think whether this is because the summer saving time? Or did I make an mistake on how the String should be parsed?
Please help. Many thanks.

Parsing String to Date without using SimpleDateFormat?

I am developing a spring application and in one of my controller i have following lines to parse from string to date and format the parsed date to required format. But again i need to parse back formatted string into date without using any SimpleDateFormat, so is it possible to do so ?
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
Date pick=dateFormat.parse(request.getParameter("pickDate"));
String pick_date=dateFormat2.format(pick);
Edit:
I found in the wikipedia that china has the locale yyyy-MM-dd. check this reference date format by country
set locale to China you'll get the required date format
Try this
String d1="12-27-2010";
Stirng[] splitdata=d1.split("-");
int month=Integer.parseInt(splitdata[0]);
int day=Integer.parseInt(splitdata[1]);
int year=Integer.parseInt(splitdata[2]);
Calender cal=Calender.getInstance(Locale.CHINA);
cal.set(year,month,day);
Date d=cal.getTime();
This should work
If you know your data format you can do that. by using simple string operations
Ex:
if your data format is
MM-dd-yyyy
then you can convert to yyyy-MM-dd like this
String d1="12-27-2010";
Stirng[] splitdata=d1.split("-");
String s2= splitdate[2]+"-"+splitdate[0]+"-"+splitdate[1];
You can use Concatenation Operator(+) for that
Yes possible; just write the code to do the parsing. Should not be that difficult ...

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