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 ...
Related
I have a date in string format like "2017-11-16" or "2017-11-16 12:59:11.243". I have to convert it to Date.
Below is my code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
Date createdOn = formatter.parse(date);
It works fine when the date is "2017-11-16 12:59:11.243". But not able to format with "2017-11-16" date.
String date is coming from URL, so it could be either with time or without time. How can I convert it into Date in spite of the fact what type of date is coming from URL?
Actually, I have to find row from the database based on the date. In the database, the date is storing in the format like 2017-11-16 12:59:11.243. But If from URL 2017-11-16 is coming then it should find according to this date.
You can modify the pars based on the presence of time,
if(dateOrDataTime.contains(":")){
//Use parser with date-time. & fetch with equal
}else{
//Use parser for date only. & fetch using date(date_time)
}
I want to convert from string to date using Java 8.
I can easily convert using SimpleDateFormat and yyyy-MM-dd format
String startDate2="2017-03-24";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(new java.sql.Date(sdf1.parse(startDate2).getTime()));
output:
2017-03-24
String startDate2="2017-03-24";
SimpleDateFormat sdf1 = new SimpleDateFormat("uuuu-MM-dd");
System.out.println(new java.sql.Date(sdf1.parse(startDate2).getTime()));
But when I use 'uuuu-MM-dd' instead of 'yyyy-MM-dd'
output :
1970-03-24(wrong)
now in Java 8:
String startDate1="2017-03-23";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
But I don't know how I can get the date which would be sql date type same as above correct output.
java.sql.Date has a static valueOf method that takes a Java 8 LocalDate so you can do:
String startDate1 = "2017-03-23";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
LocalDate date = LocalDate.parse(startDate1, formatter);
java.sql.Date sqlDate = java.sql.Date.valueOf(date);
As far as I can see, you have a text in yyyy-MM-dd format and you want it in uuuu-MM-dd format. So you need two formats:
String startDate2="2017-03-24";
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat targetFormat = new SimpleDateFormat("uuuu-MM-dd");
java.sql.Date date = new java.sql.Date(sourceFormat.parse(startDate2).getTime());
String formattedAsDayOfWeek = targetFormat.format(date);
System.out.println(formattedAsDayOfWeek);
Bottom line is that Date contains a millisecond value. java.sql.Date.toString() uses the yyyy-MM-dd format regardless how you parsed it. java.util.sql.Date uses another format: EEE MMM dd hh:mm:ss zzz yyyy with English Locale.
You can do other formatting with DateFormat -s.
I presume you need the uuuu-MM-dd format for inserting data to the database. What does that logic look like?
You don’t want a java.sql.Date. You want a LocalDate. Your SQL database wants one too.
String startDate2 = "2017-03-24";
LocalDate date = LocalDate.parse(startDate2);
System.out.println(date);
Output is:
2017-03-24
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time including LocalDate parse this format as their default, that is, without any explicit formatter.
You also note that we don’t need any explicit formatter for formatting back into uuuu-MM-dd format for the output. The toString method implicitly called from System..out.println() produces ISO 8601 format back.
Assuming that you are using a JDBC 4.2 compliant driver (I think we all are now), I am taking the way to pass it on to your SQL database from this question: Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2:
myPreparedStatement.setObject ( 1 , date ); // Automatic detection and conversion of data type.
Refer to the linked question for much more detail.
The java.sql.Date class is poorly designed, a true hack on top of the already poorly designed java.util.Date class. Both classes are long outdated. Don’t use any of them anymore.
One more link: Wikipedia article: ISO 8601
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
I need to convert a SQL Server timestamp format (stored on Timestamp java data type) into this format yyyy-mm-ddThh:mm:ss.sssZ (it's the date format parsed by Alfresco)
How can I do it?
thanks for your time!
Andrea
Try this SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );
String yourformattedDate = sdf.format(yourDate);
You could try and get the time (in ms) from your TimeStamp instance, create a Date instance and use the DateFormatter class to format it anyway you want. That is, assuming DateFormatter supports the format you want.
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()
)
);