java日期操作(转的别人的)
/**
* 标准时间格式
*/
private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat(
"MM/dd/yyyy HH:mm" );
/**
* 带时分秒的标准时间格式
*/
private static final SimpleDateFormat DATE_TIME_EXTENDED_FORMAT = new SimpleDateFormat(
"MM/dd/yyyy HH:mm:ss" );
/**
* ORA标准日期格式
*/
private static final SimpleDateFormat ORA_DATE_FORMAT = new SimpleDateFormat(
"yyyyMMdd" );
/**
* ORA标准时间格式
*/
private static final SimpleDateFormat ORA_DATE_TIME_FORMAT = new SimpleDateFormat(
"yyyyMMddHHmm" );
/**
* 带时分秒的ORA标准时间格式
*/
private static final SimpleDateFormat ORA_DATE_TIME_EXTENDED_FORMAT = new SimpleDateFormat(
"yyyyMMddHHmmss" );
/**
* 创建一个标准日期格式的克隆
*
* @return 标准日期格式的克隆
*/
public static synchronized DateFormat getDateFormat()
{
/**
* 详细设计: 1.返回DATE_FORMAT
*/
SimpleDateFormat theDateFormat = ( SimpleDateFormat )
DATE_FORMAT.clone();
theDateFormat.setLenient( false );
return theDateFormat;
}
/**
* 创建一个标准时间格式的克隆
*
* @return 标准时间格式的克隆
*/
public static synchronized DateFormat getDateTimeFormat()
{
/**
* 详细设计: 1.返回DATE_TIME_FORMAT
*/
SimpleDateFormat theDateTimeFormat = ( SimpleDateFormat ) DATE_TIME_FORMAT
.clone();
theDateTimeFormat.setLenient( false );
return theDateTimeFormat;
}
/**
* 创建一个标准ORA日期格式的克隆
*
* @return 标准ORA日期格式的克隆
*/
public static synchronized DateFormat getOraDateFormat()
{
/**
* 详细设计: 1.返回ORA_DATE_FORMAT
*/
SimpleDateFormat theDateFormat = ( SimpleDateFormat ) ORA_DATE_FORMAT
.clone();
theDateFormat.setLenient( false );
return theDateFormat;
}
/**
* 创建一个标准ORA时间格式的克隆
*
* @return 标准ORA时间格式的克隆
*/
public static synchronized DateFormat getOraDateTimeFormat()
{
/**
* 详细设计: 1.返回ORA_DATE_TIME_FORMAT
*/
SimpleDateFormat theDateTimeFormat = ( SimpleDateFormat )
ORA_DATE_TIME_FORMAT.clone();
theDateTimeFormat.setLenient( false );
return theDateTimeFormat;
}
/**
* 将一个日期对象转换成为指定日期、时间格式的字符串。 如果日期对象为空,返回一个空字符串,而不是一个空对象。
*
* @param theDate
* 要转换的日期对象
* @param theDateFormat
* 返回的日期字符串的格式
* @return 转换结果
*/
public static synchronized String toString( Date theDate,
DateFormat theDateFormat )
{
/**
* 详细设计:
* 1.theDate为空,则返回""
* 2.否则使用theDateFormat格式化
*/
if ( theDate == null )
return "";
return theDateFormat.format( theDate );
}
}
java日期操作 及 Timer定时器
2006-11-15 17:17
作者:罗代均,ldj_work#126.com ,转载请保持完整性.
转自:http://hi.baidu.com/luodaijun/blog/item/304d19174ecefb014a90a79b.html
1.基础
Date,这个大家都认识了,用于保存日期信息,但不推荐进行日期操作及初始化特定日期
Calendar及其子类GregorianCalendar:日历类,日期操作,初始化特定日期。
DateFormat及其子类SimpleDateformat: 日期格式化,日期的默认显示方式不适合中国人,所以需要格式化为中国人常用的格式来显示。
取得当期日期, Date date=new Date();
初始化特定日期:假设我们要得到日期为2006-10-27日的对象,需要按如下方式获得。
Calendar cal = new GregorianCalendar(2006, 9, 27,0,0,0);
Date date = cal.getTime();
注意:date,getTime()取得的是当期时间的毫秒数,月份比实际的减1
GregorianCalendar构造方法参数依次为:年,月-1,日,小时,分,秒
格式化为我们熟悉的方式显示:
DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH;mm:ss");
String chinesedate = format.format(date);
日期 年,月,日,分,秒的取得
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
注意:月份,实际的月份要比Clendar得到的加1,因为java月份是从0~11
2.日期基本操作
得到两个日期相差的天数
Date endDate=..
Date startDate = ...
相差天数 int days=(int) ((endDate.getTime()-startDate.getTime())/(1000*24*60*60)+0.5);
得到某个月的天数
Calendar cal = Calendar.getInstance();
int month=cal.getActualMaximum(Calendar.DAY_OF_MONTH);
日期加1天
cal.add(Calendar.DATE, 1);//日期加1天
Calendar.YEAR,Calendar.MONTH,Calendar.WEEK_OF_YEAR),分别是年,月,周
3,java.sql,Date()和java.util.Date();
前面我们说的都是java.util.Date类,java.sql.Date类是操作数据库用的日期类型
java.util.Date date=....
java.sql.Date sqldate=new java.sql.Date(date.getTime());
也可以这样:String date="2005-11-10";
java.sql.Date sqlDate=java.sql.Date.valueOf(date);
4,定时器
a,编写类,实现TimeTask接口,定时执行的代码写入run()方法中
b. timer.schedule(TimeTask子类对象, 开始执行的日期, 周期);
周期为毫秒数
例子:
类MyTask:
import java.util.*;
public class MyTask extends TimerTask {
public void run() {
System.out.println("MyTask 正在执行...");
}
}
类TimerDemo:
import java.util.Timer;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
public class TimerDemo {
public static void main(String[] args) {
Timer timer = new Timer();
MyTask task = new MyTask();
Calendar cal = new GregorianCalendar(2006, 9, 28, 12, 49, 0);
Date date = cal.getTime();
System.out.println("date :" + date.toLocaleString());
timer.schedule(task, date, 1000);
}
}
===================================
将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,;
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
***************************************