Java.util.Date and Java.sql.Date differences and mutual transformation (RPM)

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/qin_zhimou/article/details/55509769
共同点:都有getTime方法返回毫秒数,可以直接构建
不同点:
1、java.sql.Date是针对SQL语句使用的,它只包含日期而没有时间部分,一般在读写数据库的时候用,PreparedStament的setDate()的参数和ResultSet的getDate()方法的都是java.sql.Date
2、java.util.Date是在除了SQL语句的情况下面使用,一般是日常日期字段
3、java.util.Date 是 java.sql.Date 的父类,Namely: Inheritance relation: Java.lang.Object--"java.util.Date--" java.sql.Date
相互转化:
java.sql.Date转为java.util.Date
java.sql.Datedate=new java.sql.Date();
java.util.Dated=new java.util.Date(date.getTime());
java.util.Date转为java.sql.Date
java.util.DateutilDate=new Date();
java.sql.DatesqlDate=new java.sql.Date(utilDate.getTime());
java.util.DateutilDate=new Date();
java.sql.DatesqlDate=new java.sql.Date(utilDate.getTime());
java.sql.TimesTime=new java.sql.Time(utilDate.getTime());
java.sql.Timestampstp=new java.sql.Timestamp(utilDate.getTime());
这里所有时间日期都可以被SimpleDateFormat格式化format()
SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
f.format(stp);
f.format(sTime);
f.format(sqlDate);
f.format(utilDate)
java.sql.DatesqlDate=java.sql.Date.valueOf(" 2005-12-12");
utilDate=new java.util.Date(sqlDate.getTime());
另类取得年月日的方法:
import java.text.SimpleDateFormat;
import java.util.*;
java.util.Datedate= new java.util.Date();
如果希望得到YYYYMMDD的格式SimpleDateFormat
sy1=new SimpleDateFormat("yyyyMMDD");
String dateFormat=sy1.format(date);
如果希望分开得到年,月,日SimpleDateFormat
sy=new SimpleDateFormat("yyyy");
SimpleDateFormat sm=new SimpleDateFormat("MM");
SimpleDateFormat sd=new SimpleDateFormat("dd");
String syear=sy.format(date);
String smon=sm.format(date);
String sday=sd.format(date);

Java.util.Date and Java.sql.Date differences and mutual transformation (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.