Mr.*_*ary 24 java date type-conversion
我有一个字符串形式的日期.我必须将其更改为Sql Date.所以为此我使用了以下代码.
String startDate="01-02-2013";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-mm-yyyy");
java.util.Date date = sdf1.parse(startDate);
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
Run Code Online (Sandbox Code Playgroud)
当我使用上面的代码并运行它.我得到了以下输出.
2013-01-01.
Run Code Online (Sandbox Code Playgroud)
这里月未正确转换.
请告诉我问题出在哪里,并提供示例代码以获得正确的结果?
Boh*_*ian 44
mm是分钟.你想MM为月:
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
Run Code Online (Sandbox Code Playgroud)
不要心疼 - 这个确切的错误会出现很多.
mm 代表"分钟".MM改为使用:
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
Run Code Online (Sandbox Code Playgroud)
这是将字符串转换为 util date 和 sql date 的简单方法
String startDate="12-31-2014";
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy");
java.util.Date date = sdf1.parse(startDate);
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
Run Code Online (Sandbox Code Playgroud)
您需要使用MMasmm代表minutes。
有两种产生月份模式的方法。
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01
Run Code Online (Sandbox Code Playgroud)
完整的代码片段:
String startDate="01-Feb-2013"; // Input String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
System.out.println(sqlStartDate); // Outputs : 2013-02-01
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107924 次 |
| 最近记录: |