当前位置: 移动技术网 > IT编程>开发语言>Java > java常见日期格式转换以及日期的获取

java常见日期格式转换以及日期的获取

2018年09月08日  | 移动技术网IT编程  | 我要评论

package com.test.testboot.singlemodel;
import java.text.simpledateformat;
import java.util.date;
public class test {
    public static void main(string[] args) {
 
        /**
         * date 转 string
         */
        date date = new date();
        string datestr = new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date);       
        system.out.println(datestr);
        
        
        /**
         *string 转  date
         */
        string ss = "2016-10-24 21:59:06";
        simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
        try {
            date d = sdf.parse(ss);
            system.out.println(d);
        } catch (parseexception e) {
            e.printstacktrace();
        }

 

        /**
         * 本月第一天
         */
        calendar monthca = calendar.getinstance();    
        monthca.add(calendar.month, 0);    
        monthca.set(calendar.day_of_month,1);            
        string monthfirstday = sdf.format(monthca.gettime());    //本月第一天
        system.out.println(monthfirstday);

       

         /**
         * 本月最后一天
         */
        calendar calendar = calendar.getinstance();        
        calendar.set(calendar.date, calendar.getactualmaximum(calendar.date));
        string monthlastday = sdf.format(calendar.gettime());    //本月最后一天
        system.out.println(monthlastday);

 

       /**
         * 昨天
         */
        calendar startca = calendar.getinstance();    // 得到一个calendar的实例
        startca.settime(new date());                    // 设置时间为当前时间
        startca.add(calendar.date, -1);                // 日期减1
        date sdate = startca.gettime();                //前一天的时间
        simpledateformat sd = new simpledateformat("yyyy-mm-dd");                                    
        string starttime = sd.format(sdate);                    //前一天的时间(昨天)
        system.out.println(starttime);

 

 

     /**
         * 上个月第一天
         */
        calendar lastmonthfirst = calendar.getinstance();
        lastmonthfirst.add(calendar.month, -1);
        lastmonthfirst.set(calendar.day_of_month, 1);
        string lastmonthfirstday = sd.format(lastmonthfirst.gettime());    //上个月第一天
        system.out.println(lastmonthfirstday);
        
        /**
         * 上个月最后一天
         */
        calendar lastmonthlast = calendar.getinstance();
        lastmonthlast.set(calendar.day_of_month, 1);
        lastmonthlast.add(calendar.date, -1);
        string lastmonthlastday = sd.format(lastmonthlast.gettime());        //上个月最后一天    
        system.out.println(lastmonthlastday);

         
    }
   
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网