简体   繁体   中英

Typecast sql.date to calendar

I have some code that uses the sql.date object to get the current date in the format: yyyy-MM-dd. I want to typecast that to a Calendar object that has the same format as the sql.date.

Here is the code for the sql.date:

java.util.Date now = new java.util.Date();

java.sql.Date sqlDate = new java.sql.Date( now.getTime() );

Edit:

I want to know how to put this in a Calendar object. Is it even possible to do this?

A java.sql.Date doesn't have a format. It's just a date.

To convert it to a string, use a SimpleDateFormatter with the relevant format set - or just use toString if you definitely want yyyy-MM-dd . (Unfortunately it's unclear which time zone you should use - java.sql.Date is very poorly documented in this respect. I suspect it will use the default system time zone.)

To create a Calendar object with the given date, you can just use:

Calendar calendar = Calendar.getInstance();
calendar.setTime(sqlDate);

Again, a Calendar doesn't have a text format either - it represents a point in time in a particular calendar system in a particular time zone, but nothing about a textual representation.

Java Date objects (and note that java.sql.Date is a java.util.Date ) don't have "formats". They represent an instant in time.

Calendar also doesn't have a "format".

What you're asking for doesn't make sense in java.

Consider using SimpleDateFormat to format one of these things into a String:

String str = new SimpleDateFormat("yyyy-MM-dd").format(myDate);

or if you use a Calendar object (not recommended):

String str = new SimpleDateFormat("yyyy-MM-dd").format(myCalendar.getTime()); 

Use SimpleDateFormat#format()

System.out.println(new SimpleDateFormat("yyyy-MM-dd")
                   .format(Calendar.getInstance().getTime()));

You can use the following snippet.

public class DateTest {

public static void main(String[] arg){

    Calendar calendar = Calendar.getInstance();
    //setting a valid date
    Date date = new Date(113,07,10);
    //prints the date as per format
    System.out.println("Date in YYYY-MM-DD : " +date);
    //sets the calendar with the date value in java.sql.Date instance
    calendar.setTime(date);
    //use simple date formatter to format the value in calendar instance
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println("Date formatted from Calendar instance : "+dateFormat.format(calendar.getTime()));
}

}

Please let me know what happens!

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