ITeye博客

java日期操作

thomas0988 · 2012-12-31 10:44 · 工具api · 专业知识 · 编程语言 · Markdown

http://www.blogjava.net/parable-myth/archive/2006/07/27/60275.html

将Date类型写入数据库的两种方法

先了解几个类: 

1、具体类(和抽象类相对)java.util.Date  

2、抽象类java.text.DateFormat 和它的一个具体子类,java.text.SimpleDateFormat  

3、抽象类java.util.Calendar 和它的一个具体子类,java.util.GregorianCalendar  

具体类可以被实例化, 但是抽象类却不能. 你首先必须实现抽象类的一个具体子类. 

************************************

一种将java的日期类型直接转换为SQL的日期类型的方法,比较简单但适用性狭窄,

注意一下例子在jdk下编译没有时间,但在jb和Eclipse下就有时间,不知怎么回事

——————————————

public class a {

public static void main(String[] args) {

  

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

  //PreparedStatement类型的setDate方法只接受sql.date类型,所有必须先转换

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

   try {

    //froName必须放在try中,否则编译不通过,可能froName方法抛出编译时异常了

    //经查阅 public static Class forName(String className) throws     ClassNotFoundException {...}

    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

    Connection connection = DriverManager.getConnection("jdbc:microsoft:sqlserver://192.168.0.2:1433;DatabaseName=pubs","sa","");

    PreparedStatement ps=connection.prepareStatement("update test set f1=?");

    ps.setDate(1,sqlnow);

    int i = ps.executeUpdate();

   }

    catch (Exception ex) {}

 }

}

**********************************************************

另一种是将java的date类型通过SimpleDateFormat转换为字符串,再写到sql语句中

-----------------------------------------------------------

import java.sql.*;

import java.text.SimpleDateFormat;

import java.util.Date;

public class a{

  public static void main(String[] args) {

  //之所以用kk而不用hh是因为kk是24进制的而不虽操作系统设置变动

  SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");

  Date now = new Date();

  //format()方法的返回值是String型

  System.out.println(sdf.format(date));

 }}

-----------------------------------------------------

一下是逆操作,将String转换为Date,parse()方法能抛出ParseException异常,所以你必须使用适当的异常处理技术

try{

    SimpleDateFormat sbf =new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");

    String sdate="2004-05-14 21:29:51";

    Date ddate = sbf.parse(sdate);

    System.out.println(ddate);

    }

catch (Exception ex) { }

**************************************************************

以下是副产品,我们用到的情况比较少

util.date类型

----------------------------------------------

   //1年前日期

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

   long myTime=(myDate.getTime()/1000)-60*60*24*365;

   myDate.setTime(myTime*1000);

   //明天日期

   myDate=new java.util.Date(); 

   myTime=(myDate.getTime()/1000)+60*60*24;

   myDate.setTime(myTime*1000);

  //两个时间之间的天数

   SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");

   java.util.Date date= myFormatter.parse("2003-05-1"); 

   java.util.Date mydate= myFormatter.parse("1899-12-30");

   long  day=(date.getTime()-mydate.getTime())/(24*60*60*1000);

   //加半小时

   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

   java.util.Date date1 = format.parse("2002-02-28 23:16:00");

   long Time=(date1.getTime()/1000)+60*30;

   date1.setTime(Time*1000);

   String mydate1=formatter.format(date1);

   //年月周求日期

   SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM F E");

   java.util.Date date2= formatter2.parse("2003-05 5 星期五"); 

   SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd");

   String mydate2=formatter3.format(date2);

   //求是星期几

   mydate= myFormatter.parse("2001-1-1");

   SimpleDateFormat formatter4 = new SimpleDateFormat("E");

   String mydate3=formatter4.format(mydate);

-----------------------------------------------

 now.getYear();//实际年份减去1900,如果构造函数为Date(2008,2,25)则不减1900,如果构造函数为Date(17009456745)或者setTime(17009456745)还减1900

 now.getMonth();//实际月份减去1,如果构造函数为Date(2008,2,25)则不减1,如果构造函数为Date(17009456745)或者setTime(17009456745)还减1900

 now.getDay();//*,原来是取星期,不知sun公司是咋想的,脑袋进水了。

 now.getDate();//这才是取1~31之间的日

 now.getHours();//24进制的小时

 now.getMinutes();//分

 now.getSeconds();//秒

 now.getTime();//返回1970年1月1日00:00:00起至今的毫秒数

 now.setTime(long time);//真实日期为1970年1月1日午夜+time毫秒

*************************************

日历类型的子类GregorianCalendar类型

构造函数GregorianCalendar(int year, int month, int date) ,无参数为但前时间

注意月份的表示,一月是0,二月是1,以此类推。因此最好使用单词而不是使用数字来表示月份。父类Calendar使用常量来表示月份:JANUARY, FEBRUARY...

所以1903年12月17日可以写为

GregorianCalendar aaa = new GregorianCalendar(1903, Calendar.DECEMBER, 17)

GregorianCalendar aaa = new GregorianCalendar(1903, 11, 17); 

---------------------------------------

import java.util.Date;

import java.text.DateFormat;

import java.util.GregorianCalendar;

public class a {

public static void main(String[] args) {

  DateFormat df =  DateFormat.getDateInstance(DateFormat.FULL);

  GregorianCalendar gca = new GregorianCalendar();

  //getTime()方法是将GregorianCalendar对象转换为Date对象

  gca.setTime(new Date());

  System.out.println("系统时间: " +df.format(gca.getTime()));

  //set 方法能够让我们通过简单的设置星期中的哪一天这个域来将我们的时间调整为星期五.注意到这里我们使用了常量 DAY_OF_WEEK 和 FRIDAY来增强代码的可读性.

  //如果当前为星期五时间不变

  gca.set(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.FRIDAY);

  System.out.println("下一个星期五: " +  df.format(gca.getTime()));

  //add 方法让我们能够在日期上加上数值. 

  gca.add(GregorianCalendar.DAY_OF_MONTH, 8);

  System.out.println("再加8天: " +  df.format(gca.getTime()));

  //get方法取对象中的一部分

  int i =  gca.get(GregorianCalendar.DAY_OF_MONTH);

  System.out.println(i);

}}

***************************************

Locale类:(java.util.Locale)

-----------------------------------

import java.util.Locale;

public class a {

 public static void main(String[] args) {

  Locale localeEN = new Locale("en", "US");

  //另一实例化方法=locale.ENGLISH;

  System.out.println("Display Name: " +localeEN.getDisplayName());

  System.out.println("Country: " + localeEN.getCountry());

  System.out.println("Language: " + localeEN.getLanguage());

  Locale localeFR = new Locale("fr", "FR");

  System.out.println("\nDisplay Name: " +localeFR.getDisplayName());

  System.out.println("Country: " + localeFR.getCountry());

  System.out.println("Language: " + localeFR.getLanguage());

  // 用三种语言显示本机语言、英语、法语

  System.out.println("用本语显示DisplayName: "+ localeEN.getDisplayName());

  System.out.println("用英语显示DisplayName:"+   localeEN.getDisplayName(localeEN ));

  System.out.println("用法语显示DisplayName:"+   localeEN.getDisplayName(localeFR ));

 }

}

*****************************************************

把Date以不同地域的格式显示:java.text.DateFormat

getDateTimeInstance()的前两个参数分别代表日期风格和时间风格,取值为SHORT, MEDIUM, LONG, 和 FULL

getDateInstance()方法:Java还提供了几个选择日期格式,你可以通过使用重载的getDateInstance(int style)获得。出于方便的原因,DateFormat提供了几种预置的常量,你可以使用这些常量参数SHORT, MEDIUM, LONG, 和FULL

-----------------------------------------------

import java.util.Locale;

import java.text.DateFormat;

import java.util.Date;

public class a {

  public static void main(String[] args) {     

    Date now=new Date();

    Locale localeCN=Locale.CHINA;

    DateFormat df=DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL,localeCN);

    System.out.println(df.format(now));

   //结果为2004年5月17日 星期一 下午16时38分32秒 CST  

}}

******************************************************

时区 java.util.TimeZone

--------------------------------------------------------

import java.util.TimeZone;

public class a {

  public static void main(String[] args) {

  // 系统时区

  TimeZone timeZoneFL = TimeZone.getDefault();

  System.out.println("\n" + timeZoneFL.getDisplayName());

  System.out.println("与GMT相差的微秒数: " + timeZoneFL.getRawOffset());

  System.out.println("Uses daylight saving: " + timeZoneFL.useDaylightTime());

  //通过“时区字符串ID”指定时区

  TimeZone timeZoneLondon = TimeZone.getTimeZone("Europe/London");

  System.out.println("\n" + timeZoneLondon.getDisplayName());

  System.out.println("与GMT相差的微秒数: " + timeZoneLondon.getRawOffset());

  System.out.println("采用夏令时: " + timeZoneLondon.useDaylightTime());

  }}

-------------------------------------------------------

显示结果:

中国标准时间

与GMT相差的微秒数:

Uses daylight saving:false;

格林威治时间

与GMT相差的微秒数:

采用夏令时: true

********************************************************

显示不同时区的时间  df.setTimeZone(TimeZone kkk)

----------------------------------------------------

public class a {

  public static void main(String[] args) {

    Date now=new Date();

    DateFormat df=DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL);

    TimeZone timezoneCH=TimeZone.getTimeZone("China/BeiJing");

    df.setTimeZone(timezoneCH);

    System.out.println("北京时间"+df.format(now));

    TimeZone timezoneFR=TimeZone.getTimeZone("Europe/Paris");

    df.setTimeZone(timezoneFR);

    System.out.println("巴黎时间"+df.format(now));    

  }}

-----------------------------------------------------

结果如下:

北京时间2004年5月17日 星期一 上午09时31分34秒 GMT

巴黎时间2004年5月17日 星期一 上午11时31分34秒 CEST

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。