先来一个:  
取得指定月份的第一天与取得指定月份的最后一天  
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 );
 }
}

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, 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日期操作 大全的更多相关文章

  1. java日期操作大全

    摘自(http://www.blogjava.net/i369/articles/83483.html) java日期操作 大全 先来一个:  取得指定月份的第一天与取得指定月份的最后一天  http ...

  2. Java 文件操作大全

    Java 文件操作大全 //1.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if (!myFolderPat ...

  3. java日期格式大全 format SimpleDateFormat(转)

    java日期格式大全 format SimpleDateFormat   /**    * 字符串转换为java.util.Date<br>    * 支持格式为 yyyy.MM.dd G ...

  4. java日期操作常用工具

    java日期操作常用工具 package com..util; import java.sql.Timestamp; import java.text.SimpleDateFormat; import ...

  5. Java文件操作大全

    //1.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if (!myFolderPath.exists()) ...

  6. Java数据库操作大全

    1.提取单条记录 //import java.sql.*; Connection con=null; Statement stmt=null; ResultSet %%6=null; try { Cl ...

  7. java日期操作的工具类时间格式的转换

    package cn.itcast.oa.util; import java.text.ParseException; import java.text.SimpleDateFormat;import ...

  8. JAVA 日期操作

    1.用java.util.Calender来实现 Calendar calendar=Calendar.getInstance(); calendar.setTime(new Date()); Sys ...

  9. java日期操作

    //字符串转日期 public static void dt7() throws ParseException { String str_date="2015---08---08" ...

随机推荐

  1. unity3d-小案例之角色简单漫游

    准备资源 我这里从网上下载一个角色模型,里面有一组动画.有站立.奔跑.杀怪等 我们来实现角色的前后左后移动,即键盘上的WSDA键,这里因为没有行走的动画.索性就用奔跑代替了!! 暂时先不计较代码冗余的 ...

  2. java数据结构经典问题

    A:栈抽象数据类型 1.栈的主要操作 void push(int data);将data数据插入栈中. int pop();删除并返回最后一个插入栈的元素. 2.栈的辅助操作 int top();返回 ...

  3. CRM项目总结-封装PortletURLUtil

    package com.ebizwindow.crm.utils; import java.security.Key; import java.util.List; import javax.port ...

  4. mysql BLOB字段转String的方法

    1.通过sql直接转换 select CONVERT(GROUP_CONCAT(XXX) USING utf8 from usertable; 2.通过程序转换(注:本例用的是springmvc包装并 ...

  5. 匹克定理pick

    与POJ1226为例 要知道在一个格点多边形内 知道期内部的点数 Q,边上的点数L,就可以知道他的面积pick定理及 S=Q+L/2-1; 然后 还有边上的点数除了多边形的顶点外,还有一些点该怎么求呢 ...

  6. Docker 的 Web 管理工具 DockerFly

    Dockerfly是基于 Docker1.12+ (Docker API 1.24+) 开发出Docker 管理工具,提供里最基本的基于 Docker 的管理功能,目的是能够方便广大Docker初学者 ...

  7. Unity3D关于VR的Demo(一)

    https://blog.csdn.net/qq_15807167/article/details/52048998?locationNum=8&fps=1 阅读数:9716 最近有点忙,只有 ...

  8. P2880 [USACO07JAN]平衡的阵容Balanced Lineup

    P2880 [USACO07JAN]平衡的阵容Balanced Lineup RMQ RMQ模板题 静态求区间最大/最小值 (开了O2还能卡到rank9) #include<iostream&g ...

  9. 20145101《Java程序设计》第一周学习总结

    20145101 <Java程序设计>第1周学习总结 教材学习内容总结 开学的第一周,通过课上老师的介绍和课下阅读教材我简单的了解java的发展历程,了解了JVM.JRE.JDK分别是什么 ...

  10. 20145106 java实验二

    1)复数类ComplexNumber的属性 m_dRealPart: 实部,代表复数的实数部分 m_dImaginPart: 虚部,代表复数的虚数部分 public class ComplexNumb ...