简体   繁体   中英

Java Split Date Value returned from DB to into separte date and time String

I am reading a date column from the Oracle DB.

The column type is Date .

Example Date data is: 2011-12-06 14:28:12

Now when I am reading this date I want to split the date part into a separate String and Time part into another.

// here's the code I am working with.

DateFormat df = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss"); 

// some loop.
    SomeBean bean =  new SomeBean();
    Date date  = convertTimestamp(rs.getTimestamp("DATE_VAL"));
    bean.setTime(date==null?"":convertToTimeStamp(date,true));
    bean.setDate(date==null?"": df.format(date));           
// end some loop.

private java.util.Date convertTimestamp(java.sql.Timestamp timestamp) {
    if (timestamp == null)
        return null;
    else
        return new java.util.Date(timestamp.getTime());
}

private  String convertToTimeStamp(Date date, boolean showSeconds) {
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    return convertToTimeStamp(c, showSeconds);
}   

public static String convertToTimeStamp(Calendar time, boolean showSeconds) {
    String hours = Integer.toString(time.get(Calendar.HOUR_OF_DAY));
    if (hours.length() == 1) {
        hours = '0' + hours;
    }
    String minutes = Integer.toString(time.get(Calendar.MINUTE));
    if (minutes.length() == 1) {
        minutes = '0' + minutes;
    }
    if (showSeconds) {
        String seconds = Integer.toString(time.get(Calendar.SECOND));
        if (seconds.length() == 1) {
            seconds = '0' + seconds;
        }
        return hours + ":" + minutes + ":" + seconds;
    } else {
        return hours + ":" + minutes;
    }
}

Please help. Your help will be appreciated.

Thanks

first of all I would recommend to have a look at Joda-Time : it has a lot of easy going date and time functions. (a lot easier than the java date).

converting java.sql.Date to joda DateTime I use:

public static DateTime convertSqlDateToDateTime(java.sql.Date sqlDate){
    Calendar c = Calendar.getInstance();
    c.setTime(sqlDate);
    //note: java months are between 0 and 11:
    DateTime dt=new DateTime(c.get(Calendar.YEAR),c.get(Calendar.MONTH)+1,c.get(Calendar.DAY_OF_MONTH),c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),c.get(Calendar.SECOND),c.get(Calendar.MILLISECOND));
    return dt;
}

This will at least save you one function, and will maybe help you to your solution.

To convert a java.sql.TimeStamp to joda DateTime:

public static DateTime convertSqlTimeStampToDateTime(java.sql.Timestamp sqlTimestamp){
    Calendar c = Calendar.getInstance();
    c.setTime(sqlTimestamp);
    //note: java months are between 0 and 11:
    DateTime dt=new DateTime(c.get(Calendar.YEAR),c.get(Calendar.MONTH)+1,c.get(Calendar.DAY_OF_MONTH),c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE),c.get(Calendar.SECOND),c.get(Calendar.MILLISECOND));
    return dt;
}

Second of all, why not use the DateFormatter to convert your date to a string you want?

Sticking to the Joda DateTime, use:

/**
 * Converts a DateTime to a string using the given pattern (format)
 * @param dateTime
 * @param pattern
 * @return
 */
public static String convertDateTimeToPattern(DateTime dateTime,String pattern){
    DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
    return dateTime.toString(fmt);
}

U can use the same formats as the java.Date and Time formatters:

pattern = "DD-MM-YYYY" (dutch notation) or "YYYY-MM-DD" (uk notation) and for time pattern="hh:mm:ss"

if you want to stick to your method, create another SimpleDateFormat, and use this last pattern ("hh:mm:ss") to create a time String.

Please, at leaste change this function:

public static String convertToTimeStamp(Calendar time, boolean showSeconds)

in to:

public static String convertToTimeStamp(Date date, boolean showSeconds) {
    String pattern = "hh:mm:ss";
    if (!showSeconds) {
        pattern = "hh:mm";
    }
    DateFormat df = new SimpleDateFormat(pattern);
    return df.format(date);
}

In your last remark, i gues you asked for:

public static String convertToDateString(Date date) {
    String pattern = "YYYY-MM-DD"; 
    //(or another date format, like in dutch: "DD-MM-YYY"
    DateFormat df = new SimpleDateFormat(pattern);
    return df.format(date);
}

Besides some questionable quality of code, your main problem is these conditions reversed

bean.setTime(date!=null?"":convertToTimeStamp(date,true));                       
bean.setDate(date!=null?"": df.format(date));

should be replaced with:

bean.setTime(date==null?"":convertToTimeStamp(date,true));                       
bean.setDate(date==null?"": df.format(date));

使用两个SimpleDateFormat对象,一个解析Date部分,一个解析Time部分,您可以在SPACE字符上使用String.split()获取每个部分。

    DateFormat formatDate = new SimpleDateFormat("yyyy-MM-DD");
    DateFormat formatTime = new SimpleDateFormat("HH:mm:ss");
    Date now = new Date();

    System.out.println("dateOnly: " + formatDate.format(now));
    System.out.println("timeOnly: " + formatTime.format(now));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM