使用Java从MySql DATETIME字段中打印日期和时间
我在从我的MySQL数据库的DATETIME字段中获取日期时遇到问题。 我正尝试使用此DATETIME信息打印一个字段:2013-06-23 17:29:40
格式为年 - 月 - 日 - 小时:分钟:秒。
从我的数据库结果中获取日期(cal.toString()): java.util.GregorianCalendar [time = 1372001380000,areFieldsSet = true,areAllFieldsSet = true,lenient = true,zone = sun.util.calendar.ZoneInfo [id = “欧洲/巴黎”,偏移量= 3600000,dstSavings = 3600000,useDaylight = TRUE,转换= 184,lastRule = java.util.SimpleTimeZone中的[ID =欧洲/巴黎,偏移量= 3600000,dstSavings = 3600000,useDaylight = TRUE,startYear = 0,STARTMODE = 2,startMonth = 2,朝九特派= -1,startDayOfWeek = 1,开始时间= 3600000,startTimeMode = 2,endMode = 2,endMonth = 9,endday指定= -1,一个endDayOfWeek = 1,结束时间= 3600000,endTimeMode = 2]],Firstdayofweek可= 2,minimalDaysInFirstWeek = 4,ERA = 1,YEAR = 2013,MONTH = 5,WEEK_OF_YEAR = 25,WEEK_OF_MONTH = 3,DAY_OF_MONTH = 23,DAY_OF_YEAR = 174,DAY_OF_WEEK = 1,DAY_OF_WEEK_IN_MONTH = 4,AM_PM = 1,HOUR = 5,HOUR_OF_DAY = 17,MINUTE = 29,SECOND = 40,微差= 0,ZONE_OFFSET = 3600000,DST_OFFSET = 3600000]
我使用Integer.toString将int属性转换为String。 不过打印年份我得到这个:1 打印月份: 3 打印日期: 5 打印小时: 11 打印分钟: 12 打印秒数: 13
如果我这样做:
String month = Integer.toString(cal.get(Calendar.MONTH) + 1);
if (month.length() == 1)
month = "0" + month;
String day = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
if (day.length() == 1)
day = "0" + day;
String hour = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
if (hour.length() == 1)
hour = "0" + hour;
String minute = Integer.toString(cal.get(Calendar.MINUTE));
if (minute.length() == 1)
minute = "0" + minute;
String second = Integer.toString(cal.get(Calendar.SECOND));
if (second.length() == 1)
second = "0" + second;
String date= cal.YEAR + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
我得到这个,如果我打印日期字符串 :1-06-23 17:29:40
有人知道发生了什么事,我该如何打印正确的日期? 提前致谢。
一旦获得了Calendar
实例,就可以从中获取Date
实例,并使用SimpleDateFormat
格式化字符串。 例如,
Date d = cal.getTime();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String s = df.format(d); // formatted date
你得到错误字符串的原因是... cal.YEAR是Calendar
类的静态常量,其值被定义为1
。
String date= cal.YEAR + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
^^^^^^^^
这就是为什么你错了一年。
如果你应该得到年,月,日,小时,分,秒的每个值,可以这样做:
String year = String.format("%d", cal.get(Calendar.YEAR));
String month = String.format("%02d", cal.get(Calendar.MONTH)+1);
String date = String.format("%02d", cal.get(Calendar.DATE));
String hour = String.format("%02d", cal.get(Calendar.HOUR));
String minute = String.format("%02d", cal.get(Calendar.MINUTE));
String second = String.format("%02d", cal.get(Calendar.SECOND));
链接地址: http://www.djcxy.com/p/949.html
上一篇: Print using Java a date and time from a MySql DATETIME field
下一篇: Java and SOAP data client request as UTC time and save as EST time