java 将 mm-dd-yyyy 转换为 yyyy-mm-dd
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5687826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert mm-dd-yyyy to yyyy-mm-dd
提问by Roger
When I grab the current date, I pull the month, day and year, use a string builder and end up with a mm-dd-yyyy format that I put into a textview. When I save data to an sqlitedb, I just grab the date from the textview and insert it. This doesn't work well for date functions as they require yyyy-mm-dd format.
当我获取当前日期时,我会提取月、日和年,使用字符串构建器并最终得到一个放入文本视图的 mm-dd-yyyy 格式。当我将数据保存到 sqlitedb 时,我只是从 textview 中获取日期并插入它。这不适用于日期函数,因为它们需要 yyyy-mm-dd 格式。
What's the best way to handle this?
处理这个问题的最佳方法是什么?
回答by BalusC
Use two SimpleDateFormat
instances.
使用两个SimpleDateFormat
实例。
String dateString1 = "16-04-2011";
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(dateString1);
String dateString2 = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(dateString2); // 2011-04-16
// ...
But better is to just use java.util.Date
all the time to hold the value and apply formatting on the front end only. JDBC offers the PreparedStatement#setDate()
to set a java.sql.Date
in a SQL string.
但更好的是一直使用java.util.Date
来保存值并仅在前端应用格式。JDBC 提供PreparedStatement#setDate()
了java.sql.Date
在 SQL 字符串中设置 a的方法。
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));
From the other side, to get it from the DB, just use ResultSet#getDate()
and upcast it to java.util.Date
.
另一方面,要从数据库中获取它,只需使用ResultSet#getDate()
并将其上传到java.util.Date
.
Date date = resultSet.getDate("columnname");
回答by Rifat Chowdhury
Another Approach you could take:
您可以采取的另一种方法:
/**
* This Method Takes an Input String in the format of MM/dd/yyyy
* and converts it to yyyy-MM-dd
*
* @param originalString
* @return
*/
private String convertMMddyyyyToyyyyMMdd(String originalString) {
StringBuilder dateBuilder = new StringBuilder();
dateBuilder = dateBuilder.append(originalString.substring(6)).append("-").append(originalString.substring(0, 2)).append("-").append(originalString.substring(3, 5));
return dateBuilder.toString();
}