首页 文章

使用Java从MySql DATETIME字段打印日期和时间

提问于
浏览
0

我从MySQL DB的DATETIME字段打印日期时遇到问题 . 我正在尝试使用此DATETIME信息打印字段:2013-06-23 17:29:40

格式为每年 - 每月 - 小时:分钟:秒 .

Priting the date I get from my DB result (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 =欧洲/巴黎,偏移= 3600000,dstSavings = 3600000,useDaylight =真,startYear = 0,STARTMODE = 2,startMonth = 2,朝九特派= -1,startDayOfWeek = 1, STARTTIME = 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 . 但 printing the year 我明白了:1 Printing the month: 3 Printing the day: 5 Printing the hour: 11 Printing the minute: 12 Printing the seconds: 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;

如果我打印 date string :1-06-23 17:29:40,我得到了这个

有谁知道发生了什么,我怎样才能打印出正确的日期?提前致谢 .

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 类的静态constance,其值定义为 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));
    

相关问题