0

我在打印从 MySQL 数据库的 DATETIME 字段中获取的日期时遇到问题。我正在尝试使用此日期时间信息打印一个字段:2013-06-23 17:29:40

格式为 YEAR-MONTH-DAY HOURS:MINUTES:SECONDS。

打印我从数据库结果 (cal.toString()) 中获得的日期: java.util.GregorianCalendar[time=1372001380000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id ="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear =0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=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,MILLISECOND=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

有谁知道发生了什么以及如何打印正确的日期?提前致谢。

4

1 回答 1

1

获得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));
于 2013-05-31T10:34:29.417 回答