将util日期类型转换为SQL日期类型

huangapple go评论110阅读模式
英文:

util date to the sql date typecasting

问题

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

// giving error
java.sql.Date sqlDate = (java.sql.Date) utilDate;
// correct
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Why I am unable to typecast the util.date to SQL.date
英文:
java.util.Date utilDate = new java.util.Date();

// giving error
java.sql.Date sqlDate= (java.sql.Date) utilDate;
// correct
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Why I am unable typecasting the util.date to SQL.date

答案1

得分: 0

java.util.Datejava.sql.Date的父类。在Java中,父类型无法转换为子类型。

private static class A {

}

private static class B extends A {

}

public static void main(String[] args) {
    A a = new A();
    B b = new B();

    B ba = (B) a; // java.lang.ClassCastException
}
英文:

java.util.Date is a parent of java.sql.Date. In Java parent type cannot be casted to child.

private static class A {

}

private static class B extends A {

}

public static void main(String[] args) {
    A a = new A();
    B b = new B();

    B ba = (B) a; // java.lang.ClassCastException
}

答案2

得分: 0

以下是翻译好的代码部分:

{
    java.util.Calendar calender = Calendar.getInstance();
    java.util.Date dateInUtils = new java.util.Date(); 
    calender.setTime(dateInUtils);
    calender.set(Calendar.HOUR_OF_DAY, 0);
    calender.set(Calendar.MINUTE, 0);
    calender.set(Calendar.SECOND, 0);
    calender.set(Calendar.MILLISECOND, 0);    
    java.sql.Date dateInSql = new java.sql.Date(calender.getTime().getTime()); 
    System.out.println("dateInUtils:" + dateInUtils);
    System.out.println("dateInSql:" + dateInSql);
}
英文:

Can you please try the below solution to convert date in util to sql date:

{
    java.util.Calendar calender = Calendar.getInstance();
    java.util.Date dateInUtils = new java.util.Date(); 
    calender.setTime(dateInUtils);
    calender.set(Calendar.HOUR_OF_DAY, 0);
    calender.set(Calendar.MINUTE, 0);
    calender.set(Calendar.SECOND, 0);
    calender.set(Calendar.MILLISECOND, 0);    
    java.sql.Date dateInSql = new java.sql.Date(calender.getTime().getTime()); 
    System.out.println("dateInUtils:" + dateInUtils);
    System.out.println("dateInSql:" + dateInSql);
}

huangapple
  • 本文由 发表于 2020年3月15日 18:51:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/60692097.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定