如何从Java将Current date设置为MySQL date列? [英] How to set Current date to MySQL date column from Java?
问题描述
我在表中有一个DATE数据类型mysql列.我想以YYYY-MM-DD的格式从Java代码中设置该列的值
我使用以下代码测试了这些格式.
Calendar c = Calendar.getInstance();
c.setTime(new Date());
String d = c.YEAR+ "-"+c.MONTH+"-"+c.DATE;
但是,如果我在控制台中打印出该值,则会得到一些奇怪的输出.请帮忙.我还能怎么做到呢?
您需要做的是:
String d = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DATE)
如果我没记错的话,您还必须在月份中加上+1,因为它返回的是偏移量(从0开始计数),而不仅仅是月份值(对我来说这很愚蠢,但我没有做设计).>
此外,您可能希望检查 SimpleDateFormat 及其以很好的方式格式化日期的功能.
I have a DATE datatype mysql column in a table. I want to set the value of that column from my java code in the format YYYY-MM-DD
I used following code to test these formats..
Calendar c = Calendar.getInstance();
c.setTime(new Date());
String d = c.YEAR+ "-"+c.MONTH+"-"+c.DATE;
But I get some wierd output if i print out that value in console. Please help. How else can I accomplish this ?
What you have to do is:
String d = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DATE)
If I remember correctly you also have to add +1 to the month as it returns offset (counted from 0) instead of just month value (which is stupid for me, but I didn't do the design).
Also, you might like to check SimpleDateFormat and its capabilities to format a date in nice way.
这篇关于如何从Java将Current date设置为MySQL date列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!