- 获取年月日时分秒:
- package com.util;
- import java.text.DateFormat;
- import java.util.Calendar;
- import java.util.Date;
- public class Test {
- public void getTimeByDate(){
- Date date = new Date();
- DateFormat df1 = DateFormat.getDateInstance();//日期格式,精确到日
- System.out.println(df1.format(date));
- DateFormat df2 = DateFormat.getDateTimeInstance();//可以精确到时分秒
- System.out.println(df2.format(date));
- DateFormat df3 = DateFormat.getTimeInstance();//只显示出时分秒
- System.out.println(df3.format(date));
- DateFormat df4 = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL); //显示日期,周,上下午,时间(精确到秒)
- System.out.println(df4.format(date));
- DateFormat df5 = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG); //显示日期,上下午,时间(精确到秒)
- System.out.println(df5.format(date));
- DateFormat df6 = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT); //显示日期,上下午,时间(精确到分)
- System.out.println(df6.format(date));
- DateFormat df7 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM); //显示日期,时间(精确到分)
- System.out.println(df7.format(date));
- }
- public void getTimeByCalendar(){
- Calendar cal = Calendar.getInstance();
- int year = cal.get(Calendar.YEAR);//获取年份
- int month=cal.get(Calendar.MONTH);//获取月份
- int day=cal.get(Calendar.DATE);//获取日
- int hour=cal.get(Calendar.HOUR);//小时
- int minute=cal.get(Calendar.MINUTE);//分
- int second=cal.get(Calendar.SECOND);//秒
- int WeekOfYear = cal.get(Calendar.DAY_OF_WEEK);//一周的第几天
- System.out.println("现在的时间是:公元"+year+"年"+month+"月"+day+"日 "+hour+"时"+minute+"分"+second+"秒 星期"+WeekOfYear);
- }
- public static void main(String[] args) {
- Test t=new Test();
- t.getTimeByDate();
- System.out.println("****************************");
- t.getTimeByCalendar();
- }
- }
获取日,如果大于16则+2个月,否则+1个月,输出7个月
- public static void main(String[] as) throws Exception {
- int j;
- Calendar cc = Calendar.getInstance();
- int myYear = cc.get(Calendar.YEAR);
- int myMonth = cc.get(Calendar.MONTH);
- j=cc.get(Calendar.DATE)>16?3:2;
- cc.set(Calendar.MONTH, myMonth+j);
- System.out.println(myYear+"-"+cc.get(cc.MONTH));
- for(int i=0;i<7;i++){
- cc.add(cc.MONTH, 1);
- int mm = cc.get(cc.MONTH);
- int mmm=mm==0?12:mm;
- System.out.println(myYear+"-"+mmm);
- }
- }
这里有个博客http://www.blogjava.net/xiaoyi/articles/295044.html,里面有一些常用方法的实现,可以参考,自己在优化
java中常用日期操作大全
1.计算某一月份的最大天数
1 Calendar time=Calendar.getInstance(); 2 time.clear(); 3 time.set(Calendar.YEAR,year); //year 为 int 4 time.set(Calendar.MONTH,i-1);//注意,Calendar对象默认一月为0 5 int day=time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
注:在使用set方法之前,必须先clear一下,否则很多信息会继承自系统当前时间 2.Calendar和Date的转化
(1) Calendar转化为Date
Calendar cal=Calendar.getInstance(); Date date=cal.getTime();
(2) Date转化为Calendar
Date date=new Date(); Calendar cal=Calendar.getInstance(); cal.setTime(date);
3.格式化输出日期时间 (这个用的比较多)其一
1 Date date=new Date(); 2 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 3 String time=df.format(date); 4 System.out.println(time);//2008-10-27 08:52:32
其二
1 Calendar c = Calendar.getInstance(); 2 System.out.println(c.getTime());//Mon Oct 27 08:51:21 CST 2008 3 SimpleDateFormat simpleDateTimeFormat = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss "); 4 c = Calendar.getInstance(Locale.CHINESE); 5 System.out.println(simpleDateTimeFormat.format(c.getTime()));// 2008-10-27 08:51:21
4.计算一年中的第几星期 (1)计算某一天是一年中的第几星期
1 Calendar cal=Calendar.getInstance(); 2 cal.set(Calendar.YEAR, 2006); 3 cal.set(Calendar.MONTH, 8); 4 cal.set(Calendar.DAY_OF_MONTH, 3); 5 int weekno=cal.get(Calendar.WEEK_OF_YEAR);
(2)计算一年中的第几星期是几号
1 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); 2 Calendar cal=Calendar.getInstance(); 3 cal.set(Calendar.YEAR, 2006); 4 cal.set(Calendar.WEEK_OF_YEAR, 1); 5 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); 6 System.out.println(df.format(cal.getTime()));
输出:2006-01-02 5.add()和roll()的用法(不太常用)
(1)add()方法
1 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); 2 Calendar cal=Calendar.getInstance(); 3 cal.set(Calendar.YEAR, 2006); 4 cal.set(Calendar.MONTH, 8); 5 cal.set(Calendar.DAY_OF_MONTH, 3); 6 cal.add(Calendar.DATE, -4); 7 Date date=cal.getTime(); 8 System.out.println(df.format(date)); 9 cal.add(Calendar.DATE, 4); 10 date=cal.getTime(); 11 System.out.println(df.format(date));
输出: 2006-08-30 2006-09-03(2)roll方法 1 cal.set(Calendar.YEAR, 2006); 2 cal.set(Calendar.MONTH, 8); 3 cal.set(Calendar.DAY_OF_MONTH, 3); 4 cal.roll(Calendar.DATE, -4); 5 date=cal.getTime(); 6 System.out.println(df.format(date)); 7 cal.roll(Calendar.DATE, 4); 8 date=cal.getTime(); 9 System.out.println(df.format(date));
输出: 2006-09-29 2006-09-03可见,roll()方法在本月内循环,一般使用add()方法; 6.计算两个任意时间中间的间隔天数(这个比较常用)(1)传进Calendar对象
1 public int getIntervalDays(Calendar startday,Calendar endday) { 2 if(startday.after(endday)){ 3 Calendar cal=startday; 4 startday=endday; 5 endday=cal; 6 } 7 long sl=startday.getTimeInMillis(); 8 long el=endday.getTimeInMillis(); 9 10 long ei=el-sl; 11 return (int)(ei/(1000*60*60*24));12 }13
(2)传进Date对象
1 public int getIntervalDays(Date startday,Date endday) { 2 if(startday.after(endday)){ 3 Date cal=startday; 4 startday=endday; 5 endday=cal; 6 } 7 long sl=startday.getTime(); 8 long el=endday.getTime(); 9 long ei=el-sl; 10 return (int)(ei/(1000*60*60*24));11 }
(3)改进精确计算相隔天数的方法 1 public int getDaysBetween (Calendar d1, Calendar d2) { 2 if (d1.after(d2)) { 3 java.util.Calendar swap = d1; 4 d1 = d2; 5 d2 = swap; 6 } 7 int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR); 8 int y2 = d2.get(Calendar.YEAR); 9 if (d1.get(Calendar.YEAR) != y2) { 10 d1 = (Calendar) d1.clone();11 do { 12 days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);//得到当年的实际天数13 d1.add(Calendar.YEAR, 1);14 } while (d1.get(Calendar.YEAR) != y2);15 }16 return days;17 }18
注意:通过上面的方法可以衍生出求任何时间,如要查出邮箱三周之内收到的邮件(得到当前系统时间-再得到三周前时间)用收件的时间去匹配 最好装化成 long去比较如:1年前日期(注意毫秒的转换) java.util.Date myDate=new java.util.Date(); long myTime=(myDate.getTime()/1000)-60*60*24*365; myDate.setTime(myTime*1000); String mDate=formatter.format(myDate);
7. String 和 Date ,Long 之间相互转换 (最常用)
字符串转化成时间类型(字符串可以是任意类型,只要和SimpleDateFormat中的格式一致即可)
通常我们取时间跨度的时候,会substring出具体时间--long-比较
1 java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("M/dd/yyyy hh:mm:ss a",java.util.Locale.US); 2 java.util.Date d = sdf.parse("5/13/2003 10:31:37 AM"); 3 long dvalue=d.getTime(); 4 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 5 String mDateTime1=formatter.format(d);
8. 通过时间求时间
年月周求日期
1 SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM F E"); 2 java.util.Date date2= formatter2.parse("2003-05 5 星期五"); 3 SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd"); 4 String mydate2=formatter3.format(date2);
求是星期几
mydate= myFormatter.parse("2001-1-1"); SimpleDateFormat formatter4 = new SimpleDateFormat("E"); String mydate3=formatter4.format(mydate);
9. java 和 具体的数据库结合
在开发web应用中,针对不同的数据库日期类型,我们需要在我们的程序中对日期类型做各种不同的转换。若对应数据库数据是oracle的Date类型,即只需要年月日的,可以选择使用java.sql.Date类型,若对应的是MSsqlserver 数据库的DateTime类型,即需要年月日时分秒的,选择java.sql.Timestamp类型
你可以使用dateFormat定义时间日期的格式,转一个字符串即可 1 class Datetest { 2*method 将字符串类型的日期转换为一个timestamp(时间戳记java.sql.Timestamp) 3*@param dateString 需要转换为timestamp的字符串 4*@return dataTime timestamp 5 6public final static java.sql.Timestamp string2Time(String dateString) 7throws java.text.ParseException { 8DateFormat dateFormat; 9dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS", Locale.ENGLISH);//设定格式10//dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss", Locale.ENGLISH);11dateFormat.setLenient(false);12java.util.Date timeDate = dateFormat.parse(dateString);//util类型13java.sql.Timestamp dateTime = new java.sql.Timestamp(timeDate.getTime());//Timestamp类型,timeDate.getTime()返回一个long型14return dateTime;15}1617*method 将字符串类型的日期转换为一个Date(java.sql.Date)18*@param dateString 需要转换为Date的字符串19*@return dataTime Date2021public final static java.sql.Date string2Date(String dateString)22throws java.lang.Exception { 23DateFormat dateFormat;24dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);25dateFormat.setLenient(false);26java.util.Date timeDate = dateFormat.parse(dateString);//util类型27java.sql.Date dateTime = new java.sql.Date(timeDate.getTime());//sql类型28return dateTime;29}3031public static void main(String[] args){ 32Date da = new Date();33注意:这个地方da.getTime()得到的是一个long型的值34System.out.println(da.getTime());3536由日期date转换为timestamp3738第一种方法:使用new Timestamp(long)39Timestamp t = new Timestamp(new Date().getTime());40System.out.println(t);4142第二种方法:使用Timestamp(int year,int month,int date,int hour,int minute,int second,int nano)43Timestamp tt = new Timestamp(Calendar.getInstance().get(44 Calendar.YEAR) - 1900, Calendar.getInstance().get(45 Calendar.MONTH), Calendar.getInstance().get(46 Calendar.DATE), Calendar.getInstance().get(47 Calendar.HOUR), Calendar.getInstance().get(48 Calendar.MINUTE), Calendar.getInstance().get(49 Calendar.SECOND), 0);50System.out.println(tt);5152try { 53String sToDate = "2005-8-18";//用于转换成java.sql.Date的字符串54 String sToTimestamp = "2005-8-18 14:21:12.123";//用于转换成java.sql.Timestamp的字符串55 Date date1 = string2Date(sToDate);56 Timestamp date2 = string2Time(sToTimestamp);57System.out.println("Date:"+date1.toString());//结果显示58System.out.println("Timestamp:"+date2.toString());//结果显示59}catch(Exception e) { 60e.printStackTrace();61}62}63} 64
原文链接:
JAVA日期转中文汉字:
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class DateToUpperChinese {
- private static final String[] NUMBERS = { "零", "壹", "贰", "叁", "肆", "伍",
- "陆", "柒", "捌", "玖" };
- public static synchronized String toChinese(String str) {
- StringBuffer sb = new StringBuffer();
- sb.append(getSplitDateStr(str, 0)).append(" ").append(
- getSplitDateStr(str, 1)).append(" ").append(
- getSplitDateStr(str, 2));
- return sb.toString();
- }
- public static String getSplitDateStr(String str, int unit) {
- // unit是单位 0=年 1=月 2日
- String[] DateStr = str.split("-");
- if (unit > DateStr.length)
- unit = 0;
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < DateStr[unit].length(); i++) {
- if ((unit == 1 || unit == 2) && Integer.valueOf(DateStr[unit]) > 9) {
- sb.append(convertNum(DateStr[unit].substring(0, 1)))
- .append("拾").append(
- convertNum(DateStr[unit].substring(1, 2)));
- break;
- } else {
- sb.append(convertNum(DateStr[unit].substring(i, i + 1)));
- }
- }
- if (unit == 1 || unit == 2) {
- return sb.toString().replaceAll("^壹", "").replace("零", "");
- }
- return sb.toString();
- }
- private static String convertNum(String str) {
- return NUMBERS[Integer.valueOf(str)];
- }
- public static boolean isNumeric(String str) {
- Pattern pattern = Pattern.compile("[0-9]*");
- Matcher isNum = pattern.matcher(str);
- if (!isNum.matches()) {
- return false;
- }
- return true;
- }
- public static void main(String args[]) {
- System.out.println(toChinese("2008-10-02"));
- }
- }