You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
Answer from Elliott Frisch on Stack Overflow10-31-2014
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
Videos
now I want to change the format I want to store the date in the format
dd-MMM-yyyy
You don't need an explicit conversion into the requested date format dd-MMM-yyyy.
Dates are not directly concerned with date formats. Your SQL Driver class will convert to proper database specific format before inserting into a date field of database table.
Using MySQL Driver:
// this statement will cause sql date as '2014-03-21'
new java.sql.Date( new java.until.Date().getTime() );
In most of the databases the default format is YYYY-MM-DD.
Example (MySQL):
mysql> show variables like 'date_format';
+---------------+----------+
| Variable_name | Value |
+---------------+----------+
| date_format | %Y-%m-%d |
+---------------+----------+
1 row in set (0.00 sec)
mysql> select curdate();
+------------+
| curdate() |
+------------+
| 2014-03-21 |
+------------+
1 row in set (0.05 sec)
Detailed Example:
public class SimpleDateFormat_Example {
public static void main(String[] args) throws Exception {
String dateInputPattern = "yyyy-MM-dd"; // numeric 2 digit month
String dateTargetPattern = "yyyy-MMM-dd"; // For 3 char month name
String dateString = "2014-03-20";
patternTest( dateInputPattern, dateString, dateTargetPattern );
System.out.println();
// day of month first and then 2 digit month
dateInputPattern = "yyyy-dd-MM";
dateString = "2014-21-03";
dateTargetPattern = "yyyy-MMMM-dd, EEEE"; // for Full month name
patternTest( dateInputPattern, dateString, dateTargetPattern );
} // psvm( ... )
public static void
patternTest( String dateInputPattern,
String dateString,
String dateTargetPattern ) throws Exception {
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat( dateInputPattern );
java.util.Date date = sdf.parse( dateString );
System.out.println( "Date Pattern: " + dateInputPattern );
System.out.println( "Date String : " + dateString );
System.out.println( "Date Value : " + date );
sdf.applyPattern( dateTargetPattern );
System.out.println( "Target Pattern: " + dateTargetPattern );
System.out.println( "Pattern based Date Value: " + sdf.format(date) );
java.sql.Date sqlDate = new java.sql.Date( date.getTime() );
System.out.println( "But, SQL Date: " + sqlDate );
} // patternTest( s, s, s )
} // end of class SimpleDateFormat_Example
If you run the above program you would be seeing following results.
Results:
Date Pattern: yyyy-MM-dd
Date String : 2014-03-20
Date Value : Thu Mar 20 00:00:00 IST 2014
Target Pattern: yyyy-MMM-dd
Pattern Formatted Date Value: 2014-Mar-20
But, SQL Date: 2014-03-20
Date Pattern: yyyy-dd-MM
Date String : 2014-21-03
Date Value : Fri Mar 21 00:00:00 IST 2014
Target Pattern: yyyy-MMMM-dd, EEEE
Pattern Formatted Date Value: 2014-March-21, Friday
But, SQL Date: 2014-03-21
Have a close look at SQL Date, it has the same pattern in all the outputs. The same is also matching with the result of select curdate() pattern, as shown in top of this answer.
Conclusion:
Though you set and apply specific pattern, in your scripting language, for a date type database field, it would only be stored in the default pattern defined for the database date types.
Hence, converting a pattern from yyyy-MM-dd to yyyy-MMM-dd and sending to database will not affect and change anything.
try this code
String PATTERN="yyyy-MM-dd";
SimpleDateFormat dateFormat=new SimpleDateFormat();
dateFormat.applyPattern(PATTERN);
String date1=dateFormat.format(Calendar.getInstance().getTime());
Object such as java.sql.Date and java.util.Date (of which java.sql.Date is a subclass) don't have a format of themselves. You use a java.text.DateFormat object to display these objects in a specific format, and it's the DateFormat (not the Date itself) that determines the format.
For example:
Date date = ...; // wherever you get this
DateFormat df = new SimpleDateFormat("dd MMMM yyyy");
String text = df.format(date);
System.out.println(text);
Note: When you print a Date object without using a DateFormat object, like this:
Date date = ...;
System.out.println(date);
then it will be formatted using some default format. That default format is however not a property of the Date object that you can change.
If it is for presentation you can use SimpleDateFormat straight away:
package org.experiment;
import java.sql.Date;
import java.text.SimpleDateFormat;
public class Dates {
private static SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");
public static void main(String[] args){
Date oneDate = new Date(new java.util.Date().getTime());
System.out.println(df.format(oneDate));
}
}
Your format String (yyyy-mm-dd HH:mm:ss) and your input (19-SEP-2013) don't match.
A format of dd-MMM-yyyy would be required to parse the String to a Date object
For example...
try {
String text = "19-SEP-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Date date = sdf.parse(text);
System.out.println(text + " to " + date);
} catch (ParseException exp) {
exp.printStackTrace();
}
Outputs...
19-SEP-2013 to Thu Sep 19 00:00:00 EST 2013
Try replacing the first line with
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
This should resolve the parsing error.
Further information about SimpleDateFormat, including what are valid letters, can be found in the Oracle JavaDocs.
I want to send the output in DD-MMM-YYYY format to the JSP page view.
Then you need to use a SimpleDateFormat to do so. Currently you're using the result of Date.toString(), and ignoring temp which should already have the right result.
However, you shouldn't need to parse the java.sql.Date at all - you can just pass it straight to DateFormat.format:
java.sql.Date date = /* get date from database */;
// TODO: Specify time zone and locale
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = format.format(date);
Alternatively, I suspect that JSP already has a mechanism for allowing you to pass the date straight to the JSP itself, and specify the output format there... this is really a conversion to move as close to the presentation layer as possible.
This is because you re-parse the date once it has been formatted.
date = format1.parse(input);
String temp = format2.format(date);
Date outDate = format2.parse(temp);
System.out.println(outDate);
Simply do
date = format1.parse(input);
String temp = format2.format(date);
System.out.println(temp)
Note that if you have JSTL you can format direcytly in the page:
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<fmt:formatDate value="${bean.date}" pattern="dd-MMM-yy" />
2018/Java 10
String deliverydate="02-SEP-2012";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-yyyy")
.toFormatter(Locale.UK);
LocalDate ld = LocalDate.parse(deliverydate, formatter);
System.out.println(ld);
Original answer
Look at the two Strings, 02-SEP-2012 and MM/dd/yyyy - these are not the same format.
The date parser is expecting the String to be in the same format as the formatter
String deliverydate="02-SEP-2012";
SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy");
Date date=sdf.parse(deliveryDate);
sdf=new SimpleDateFormat("MM/dd/yyyy");
System.out.println(sdf.format(date));
You should use:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Date date = sdf.parse(deliveryDate);
then to re-format:
sdf.applyPattern("MM/dd/yyyy");
System.out.println(sdf.format(date));
Date are dates. It doesn't exists a format for dates.
What you can obtain is a string with a particular format from the date.
Note that the format probably is not dd/mm/yyyy but dd/MM/yyyy because mm is for minutes, not for months.
So basically you have two possibilities:
- Save dates as Date and retrieve them as string with the requested format
- Convert dates to strings and save them as formatted strings (VARCHAR for example)
To convert a Date to a String in MySql you can use the function DATE_FORMAT
If you like to convert them in java you can use a SimpleDateFormat
There is no possibility to save the date in the specified format but yes you can set the type of that field as String (in MySql varchar) and you can save whatever you want.
The javadoc for the constructor you're using java.sql.Date(int,int,int) reads (in part),
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
so you should use (assuming you mean this year)
Date d = new Date (2015-1900,01,9);
From Java Docs,
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Code
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int year = 2014;
int month = 01;
int day = 9;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
}
output
2014-01-09
If System.out.println(sql_date); is displaying the date value as 2006-12-10 it is because it is using a default yyyy-mm-dd format, either from Java or from the operating system. It doesn't mean that the date is "wrong", it is just being displayed in a different way.
Always remember:
Date values do NOT have formats. They are just (numeric) values that correspond to a particular date.
[String] Representations of Dates do have a format. However, the format does not affect the value in any way. Whether it's 2006-12-25 or 12/25/2006 or December 25, 2006 or 2006 décembre 25 the Date value is still the same.
So, you don't need to worry about using any particular format for a Date parameter, just pass the value itself:
try (
Connection conn = DriverManager.getConnection(connStr);
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO EmployeeDetails ([Date]) VALUES (?)")) {
String month = "12"; //
String year = "2006"; // sample data
String day = "10"; //
ps.setDate(1, java.sql.Date.valueOf(year + "-" + month + "-" + day));
ps.executeUpdate();
}
System.out.println(format.format(sql_date));//12/10/2006
java.sql.Date is a sub-class of java.util.Date. So we can format for java.sql.Date same as java.util.Date.