Topic
  • 3 replies
  • Latest Post - ‏2011-06-09T07:49:43Z by jdor
SystemAdmin
SystemAdmin
2768 Posts

Pinned topic Date without time

‏2007-03-14T20:08:41Z |
How can I get a Date that is just a date for comparison? When I create a Date object it includes the time. I only want month, day, and year. Can I do it without a Calendar object?
Updated on 2011-06-09T07:49:43Z at 2011-06-09T07:49:43Z by jdor
  • SystemAdmin
    SystemAdmin
    2768 Posts

    Re: Date without time

    ‏2007-03-15T16:13:11Z  

    You can use java.sql.Date, but it's such a thin wrapper over java.util.Date that it still requires manipulation to get just a date. Effectively, what you want is all time elements to be zero. Another unfortunate aspect is that java.sql.Date has no default ( no arg ) constructor.

    You could use various divisions, but probably the most straightforward way takes advantage of the API-specified format for java.sql.Date.toString(). That is JDBC escape format yyyy-mm-dd. It's useful here because java.sql.Date.valueOf() will generate a Date using that format. Since the JDBC date escape format has no time element, you get just the date. Because java.sql.Date descends from java.util.Date, you can use it anywhere a Date is needed. Here's some example code. The last java.util.Date output is just for verification:
    code
    import java.sql.*;
    import java.util.*;

    public class DateFromSQLDate
    {

    public DateFromSQLDate()
    {
    java.util.Date d = new java.util.Date();
    java.sql.Date sd = new java.sql.Date( d.getTime() );

    System.out.println( "d.getTime(): " + d.getTime() );
    System.out.println( "d: " + d );
    System.out.println( "sd.getTime(): " + sd.getTime() );
    System.out.println( "sd: " + sd );

    sd = sd.valueOf( sd.toString() );
    System.out.println( "\nsd.getTime(): " + sd.getTime() );
    System.out.println( "sd: " + sd );

    d.setTime(sd.getTime());
    System.out.println( "d.getTime(): " + d.getTime() );
    System.out.println( "d: " + d );
    } /* end constructor */
    public static void main(String[] args)
    {
    new DateFromSQLDate();
    }

    } /* end class DateFromSQLDate */
    [/code]
  • Lu Wei
    Lu Wei
    1 Post

    Re: Date without time

    ‏2009-10-23T06:22:24Z  
    Or simply use regex:
    Date start = new Date(System.currentTimeMillis());
    String withoutTime = start.toString().replaceAll("(\\d\\d:){2}\\d\\d\\s", "");
    System.out.print(withoutTime);
  • jdor
    jdor
    1 Post

    Re: Date without time

    ‏2011-06-09T07:49:43Z  
    lol
    java.util.Date d = new Date();
    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sd.format(d));