Date && Calendar

先来一段String跟Date转换的案例

package com.wyw;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ObjectDemo {
    public static void main(String[] args){
        //String 转成 Date类型  Tue Jul 11 00:00:00 CST 2017
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2017-07-11 01:01:01");
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        //Date 转成String类型   2017-07-11 12:04:50
        String str = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        System.out.println(str);
    }
}

 再看看Calendar抽象类的基本使用

public class Test {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        /**这里需要注意,月份是从0开始赋值的*/
        calendar.set(2017,8,25,10,10,10);
        calendar.add(Calendar.MONTH,-4);
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
    }
}

运行结果:2017-05-25 10:10:10

 

public class Test {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
    }
}

运行结果:2017-08-01 17:12:07

 

给当前日期减去,年,月,日,时,分,秒

public class Test {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH,-4);
        System.out.println(calendar.get(Calendar.MONTH));
    }
}

运行结果会在当前日期减去了四个月

 

posted @ 2017-07-11 12:14  青春不打烊  阅读(106)  评论(0编辑  收藏  举报