Java--Date operations

Table of contents

1.Calendar conversion to String

2.String to Calendar

3.Date conversion to String

4.String conversion Date

5.Date to Calendar

6.Calendar converted to Date

7.Convert String to Timestamp

8.Date to TimeStamp

9 code examples:

10. Disassemble the date:

11. Find the date n days later

12.JAVA date addition and subtraction operations.

12.1. Use java.util.Calender to implement

12.2. Use java.text.SimpleDateFormat and java.util.Date to implement

12.3 Implementation using GregorianCalendar

13. Calculate the number of days between two dates?


1.Calendar conversion to String
Calendar calendat = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(calendar.getTime());
2.String to Calendar
String str="2012-5-27";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date date =sdf.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
3.Date conversion to String
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
String dateStr=sdf.format(new Date());
4.String conversion Date
String str="2012-5-27";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date date= sdf.parse(str);
5.Date to Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(new java.util.Date());
6.Calendar converted to Date
Calendar calendar = Calendar.getInstance();
java.util.Date date =calendar.getTime();
7.Convert String to Timestamp
Timestamp ts = Timestamp.valueOf("2012-1-14 08:11:00");
8.Date to TimeStamp
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = df.format(new Date());
Timestamp ts = Timestamp.valueOf(time);

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

9 code examples:
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 
   
public class HelloWorld { 
      
    public static void main(String[] args) { 
          
        //指定时间输出格式 
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
         
        Date dt = new Date(); 
        System.out.println("当前时间:" + sdf.format(dt)); 
          
        Calendar rightNow = Calendar.getInstance(); 
        rightNow.setTime(dt);         
          
        rightNow.add(Calendar.YEAR,-1);//当时日期减1年 
        System.out.println("减1年:" + sdf.format(rightNow.getTime())); 
          
        rightNow.add(Calendar.MONTH,3);//(在刚才的结果上)再加3个月 
        System.out.println("再加3个月:" + sdf.format(rightNow.getTime())); 
          
        rightNow.add(Calendar.DAY_OF_YEAR,10);//(在刚才的结果上)再加10天         
        System.out.println("再加10天:" + sdf.format(rightNow.getTime())); 
          
  
    } 
  输出结果:

当前时间:2013-02-21 09:40:49
减1年:2012-02-21 09:40:49
再加3个月:2012-05-21 09:40:49
再加10天:2012-05-31 09:40:49

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

10. Disassemble the date:


 1 Date dt = new Date();        
 2 Calendar calendar = Calendar.getInstance();
 3 calendar.setTime(dt);     
 4 System.out.println("Current date:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dt));// Current date: 2013-02-28 16:22:37
 5 System.out.println("Year:" + calendar.get(Calendar.YEAR));//Year: 2013
 6 System.out.println("Month:" + (calendar.get(Calendar.MONTH)+1));//Month: 2 - Note: The month is from 0 Starting
 7 System.out.println("Day:" + calendar.get(Calendar.DATE));//Day: 28
 8 System.out.println("Hour (12-hour format):" + calendar.get(Calendar.HOUR));//Hour: 4 (12-hour format)
 9 System. out.println("Hour (24-hour format):" + calendar.get(Calendar.HOUR_OF_DAY));//Hour: 16 (24-hour format)
10 System.out. println("Minutes:" + calendar.get(Calendar.MINUTE));//Minutes:30
11 System.out.println("Seconds:" + calendar.get (Calendar.SECOND));//Seconds: 19
12 System.out.println("this month" + calendar.get(Calendar.WEEK_OF_MONTH) + "week" );//The 5th week of this month
13 System.out.println("This year" + calendar.get(Calendar.WEEK_OF_YEAR) + "week");/ /9th week of this year    

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

11. Find the date n days later

Use the Calendar class. There is a method in this class that can add any number of days to the time to get the corresponding date.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class NDays { 
    public static void main(String[] args) { 
      Date date = new Date();   
      System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(date)); 
      Calendar cal = Calendar.getInstance(); 
      cal.setTime(date);  
      cal.add(Calendar.DATE, 100);  
      System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(cal.getTime()));
    }
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class date {
    
    public static void main(String[] args) throws ParseException {
        System.out.println(datechange(new GregorianCalendar()));//将输入的Calendar转化成yyyy-mm-dd格式的String
        System.out.println(String.valueOf(dateminus("2012-9-1")));//求出输入的yyyy-mm-dd格式的String与今天的差值
        System.out.println(dateadd(90));//计算出今天起,输入的int天后的日期
    }
12.JAVA date addition and subtraction operations.
12.1. Use java.util.Calender to implement
Calendar calendar=Calendar.getInstance();   
   calendar.setTime(new Date()); 
   System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//今天的日期 
   calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1  
   System.out.println(calendar.get(Calendar.DATE));//加1之后的日期Top 
12.2. Use java.text.SimpleDateFormat and java.util.Date to implement
Date d=new Date();   
   SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
   System.out.println("今天的日期:"+df.format(d));   
   System.out.println("两天前的日期:" + df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000)));  
   System.out.println("三天后的日期:" + df.format(new Date(d.getTime() + 3 * 24 * 60 * 60 * 1000)));
12.3 Implementation using GregorianCalendar
GregorianCalendar gc=new GregorianCalendar(); 
gc.setTime(new Date); 
gc.add(field,value); 
//value为正则往后,为负则往前 
//field取1加1年,取2加半年,取3加一季度,取4加一周,取5加一天.... 

/*
*java中对日期的加减操作
*gc.add(1,-1)表示年份减一.
*gc.add(2,-1)表示月份减一.
*gc.add(3.-1)表示周减一.
*gc.add(5,-1)表示天减一.
*以此类推应该可以精确的毫秒吧.没有再试.大家可以试试.
*GregorianCalendar类的add(int field,int amount)方法表示年月日加减.
*field参数表示年,月.日等.
*amount参数表示要加减的数量.
*
* UseDate.java 测试如下:
*/
package temp.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
public class UseDate {

    Date d=new Date();
    GregorianCalendar gc =new GregorianCalendar();
    SimpleDateFormat sf  =new SimpleDateFormat("yyyy-MM-dd");

    public String getYears()
    {
        gc.setTime(d);
        gc.add(1,+1);
        gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

        return sf.format(gc.getTime());
    }

    public String getHalfYear()
    {
        gc.setTime(d);
        gc.add(2,+6);
        gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

        return sf.format(gc.getTime());
    }
    public String getQuarters()
    {
        gc.setTime(d);
        gc.add(2,+3);
        gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

        return sf.format(gc.getTime());
    }

    public String getLocalDate()
    {
        return sf.format(d);
    }


    public static  void  main(String[] args)
    {
        UseDate ud= new UseDate();
        System.out.println(ud.getLocalDate());
        System.out.println(ud.getYears());
        System.out.println(ud.getHalfYear());
        System.out.println(ud.getQuarters());
    }

}


//----------------------------------------------------
GregorianCalendar gc=new GregorianCalendar();
        
        try {
            gc.setTime( new SimpleDateFormat("yyyyMM").parse("200901"));
            gc.add(2, -Integer.parseInt("7"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(new SimpleDateFormat("yyyyMM").format(gc.getTime())); 

运行结果:200806
13. Calculate the number of days between two dates?
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");     
long to = df.parse("2008-4-25").getTime();     
long from = df.parse("2008-1-20").getTime();     
System.out.println((to - from) / (1000 * 60 * 60 * 24)); 

  //The following calculates the date difference (target day-today)

//缺陷:S传入时必须已经满足yyyy-mm-dd的格式。
    public static long dateminus(String S) throws ParseException{  
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date dt=format.parse(S);
             
        Calendar endDate=Calendar.getInstance();
        endDate.setTime(dt);
        Long e=endDate.getTimeInMillis();
        
        Calendar currentDate=Calendar.getInstance();
        currentDate.setTime(new Date());
        Long c=currentDate.getTimeInMillis(); 
        Long t=e-c;
        return format(t);  
    }
    
    public static long format(long ms) {//将毫秒数换算成x天x时x分x秒x毫秒  
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;
        long day = ms / dd+1;
        return day;
    }


//The following calculates the date sum and calculates the date one day from today.

public static String dateadd(int day){
        Calendar c=new GregorianCalendar();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String s=String.valueOf(datechange(c));
        String S=null;
    
            Date d;
            try {
                d = df.parse(s);
                for (int i = 0; i < day; i++) {
                    d=new Date(d.getTime()+60*60*24*1000);//由于当day大于25时,会溢出(int放不下),所以只能每次只加1天,加day次。
                }
            S=df.format(d);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        return S;
    }


//The following converts the incoming Calendar type data into yyyy-mm-dd format

public static String datechange(Calendar c){
        return String.valueOf(c.get(c.YEAR))
                +"-"+(String.valueOf(c.get(c.MONTH)+1).length()==1?"0"+String.valueOf(c.get(c.MONTH)+1):String.valueOf(c.get(c.MONTH)+1))
                +"-"+(String.valueOf(c.get(c.DAY_OF_MONTH)).length()==1?"0"+String.valueOf(c.get(c.DAY_OF_MONTH)):String.valueOf(c.get(c.DAY_OF_MONTH)));
    }


//The following will truncate the date with hours, minutes and seconds read from the database into the form of yyyy-mm-dd

public static String dateshort(String S){
        return S.substring(0,10);
    }
    
    public static int getyear(String S){
        return Integer.parseInt(S.substring(0, 4));
    }
}


Method of taking a certain day (ignoring the specific time)  

select * from table where DATE(reg_time)="2014-10-22"
//        String startTimeString = date+" 00:00:00";
//        String ednTimeString = date+" 23:59:59";

Guess you like

Origin blog.csdn.net/lalate/article/details/134744740