我想以yyyy-mm-dd的格式存储今天的日期.在存储之前我已经花了今天的日期,格式化它并再次解析格式化的字符串到目前为止.它以不同于我想要的格式提供输出日期.我如何获取日期,将其格式化为'yyyy-mm-dd'并再次将其转换为日期并希望输出格式为'yyyy-mm-dd'.请找到以下代码并告诉我哪里出错了
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = new java.util.Date();
java.util.Date date1;
String datestring=dateFormat.format(date);
try {
date1=dateFormat.parse(datestring);
System.out.print(date1);
} catch (ParseException ex) {
Logger.getLogger(accordcclass.class.getName()).log(Level.SEVERE, null, ex);
}
Run Code Online (Sandbox Code Playgroud)
我得到的上述代码的输出是截至2013年3月7日00:00:00 GMT.但我希望输出为2013-01-07
小智 6
我遇到了同样的问题,这就是我所做的:
DateFormat inputDateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");
DateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
System.out.println(outputDateFormat.format(inputDateFormat.parse("09-SEP-2013 10:00")));
Run Code Online (Sandbox Code Playgroud)
这样我就可以用原始格式解析日期并以数据库兼容格式输出.
有人提到使用PreparedStatement是可能的,但我不想这样做.
不要使用Date对象进行打印,直接使用您的datestring变量.使用Date将toString使用Locale.格式化的将调用.
编辑:添加如果您想要Date使用格式存储变量,它不会那样工作.A Date不包含格式,它只代表时间.如果您希望它与当前Locale格式不同,如何在GUI,控制台或其他任何地方显示它,您需要指定格式.