java日期操作 大全
取得指定月份的第一天与取得指定月份的最后一天
http://iamin.blogdriver.com/iamin/847990.html
}
}
我来个简单点的,也许有点用
int hour = now.get(Calendar.HOUR);
int min = now.get(Calendar.MINUTE);
int sec = now.get(Calendar.SECOND);
在最近的一个OA中,我需要判断两个日期是否是同一周,根据一个给定的日期获得所属周的周一和周五的日期。
在完成以上任务时,我发现Calendar 的确是一个功能强大的class。
);
return gc;
}

/** *//**
* 将日期对象转换成为指定ORA日期、时间格式的字符串形式。如果日期对象为空,返回 一个空字符串对象,而不是一个空对象。
*
* @param theDate
* 将要转换为字符串的日期对象。
* @param hasTime
* 如果返回的字符串带时间则为true
* @return 转换的结果
*/
public static synchronized String toOraString( Date theDate, boolean hasTime )
{
/** *//**
* 详细设计:
* 1.如果有时间,则设置格式为getOraDateTimeFormat()的返回值
* 2.否则设置格式为getOraDateFormat()的返回值
* 3.调用toString(Date theDate, DateFormat
* theDateFormat)
*/
DateFormat theFormat;
if ( hasTime )
{
theFormat = getOraDateTimeFormat();
}
else
{
theFormat = getOraDateFormat();
}
return toString( theDate, theFormat );
}

/** *//**
* 将日期对象转换成为指定日期、时间格式的字符串形式。如果日期对象为空,返回 一个空字符串对象,而不是一个空对象。
*
* @param theDate
* 将要转换为字符串的日期对象。
* @param hasTime
* 如果返回的字符串带时间则为true
* @return 转换的结果
*/
public static synchronized String toString( Date theDate, boolean hasTime )
{
/** *//**
* 详细设计:
* 1.如果有时间,则设置格式为getDateTimeFormat的返回值
* 2.否则设置格式为getDateFormat的返回值
* 3.调用toString(Date theDate, DateFormat theDateFormat)
*/
DateFormat theFormat;
if ( hasTime )
{
theFormat = getDateTimeFormat();
}
else
{
theFormat = getDateFormat();
}
return toString( theDate, theFormat );
}

/** *//**
* 标准日期格式
*/
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"MM/dd/yyyy" );
/** *//**
* 标准时间格式
*/
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 );
}
}

|
作者:罗代均,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,getTime()取得的是当期时间的毫秒数,月份比实际的减1 GregorianCalendar构造方法参数依次为:年,月-1,日,小时,分,秒 格式化为我们熟悉的方式显示: DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH;mm:ss"); 日期 年,月,日,分,秒的取得 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 { 类TimerDemo: import java.util.Timer; public class TimerDemo { |
===================================
将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
*******************************************************
java日期操作 大全的更多相关文章
- java日期操作大全
摘自(http://www.blogjava.net/i369/articles/83483.html) java日期操作 大全 先来一个: 取得指定月份的第一天与取得指定月份的最后一天 http ...
- Java 文件操作大全
Java 文件操作大全 //1.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if (!myFolderPat ...
- java日期格式大全 format SimpleDateFormat(转)
java日期格式大全 format SimpleDateFormat /** * 字符串转换为java.util.Date<br> * 支持格式为 yyyy.MM.dd G ...
- java日期操作常用工具
java日期操作常用工具 package com..util; import java.sql.Timestamp; import java.text.SimpleDateFormat; import ...
- Java文件操作大全
//1.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if (!myFolderPath.exists()) ...
- Java数据库操作大全
1.提取单条记录 //import java.sql.*; Connection con=null; Statement stmt=null; ResultSet %%6=null; try { Cl ...
- java日期操作的工具类时间格式的转换
package cn.itcast.oa.util; import java.text.ParseException; import java.text.SimpleDateFormat;import ...
- JAVA 日期操作
1.用java.util.Calender来实现 Calendar calendar=Calendar.getInstance(); calendar.setTime(new Date()); Sys ...
- java日期操作
//字符串转日期 public static void dt7() throws ParseException { String str_date="2015---08---08" ...
随机推荐
- 接口自动化测试框架搭建 – Java+TestNG 测试Restful service
接口自动化测试 – Java+TestNG 测试 Restful Web Service 关键词:基于Rest的Web服务,接口自动化测试,数据驱动测试,测试Restful Web Service, ...
- Python线程,进程,携程,I/O同步,异步
只有本人能看懂的-Python线程,进程,携程,I/O同步,异步 举个栗子: 我想get三个url,先用普通的for循环 import requests from multiprocessing im ...
- C#在splitContainer1控件和panel控件中显示窗体
现在有两个窗体 Form1 和Form2 Form1中有控件splitContainer1 和panel .控件.我们希望Form2在splitContainer1或者panel控件中显示 1:首先看 ...
- Lintcode: Find Peak Element
There is an integer array which has the following features: * The numbers in adjacent positions are ...
- Linux系统——LNMP分离式部署
#### 安装nginx ```[root@localhost ~]# tar xf nginx-1.10.2.tar.gz -C /usr/src/[root@localhost ~]# cd /u ...
- 【介绍+安装】Nginx的介绍和安装详解
== 介绍和安装 == Nginx是一个自由.开源.高性能及轻量级的HTTP服务器及反转代理服务器, 其性能与IMAP/POP3代理服务器相当.Nginx以其高性能.稳定.功能丰富.配置简单及占用系统 ...
- js匿名自执行函数中闭包的高级使用(---------------------------******-----------------------------)
先看看最常见的一个问题: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...
- Root :: AOAPC I: Beginning Algorithm Contests (Rujia Liu) Volume 7. Graph Algorithms and Implementation Techniques
uva 10803 计算从任何一个点到图中的另一个点经历的途中必须每隔10千米 都必须有一个点然后就这样 floy 及解决了 ************************************* ...
- linux常用命令:ping 命令
Linux系统的ping 命令是常用的网络命令,它通常用来测试与目标主机的连通性,我们经常会说“ping一下某机器,看是不是开着”.不能打开网页时会说“你先ping网关地 址192.168.1.1试试 ...
- 一个快速检测系统CPU负载的小程序
原理说明 在对服务器进行维护时,有时也遇到由于系统 CPU(利用率)负载过高导致业务中断的情况.服务器上可能运行多个进程,查看单个进程的 CPU 都是正常的,但是整个系统的 CPU 负载可能是异常的. ...