java获取指定时间的年月日

 

作者:Night Silent
链接:http://www.zhihu.com/question/35650798/answer/63983440
来源:知乎
著作权归作者所有,转载请联系作者获得授权。

1. java 7 及之前版本
1.1 使用 java.util.Calendar (不推荐)
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Demo {
    public static void main(String[] args) throws ParseException {
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2015-09-17 20:27:00");
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1; // 0-based!
        int day = now.get(Calendar.DAY_OF_MONTH);

        System.out.println("year: " + year);
        System.out.println("month: " + month);
        System.out.println("day: " + day);
    }
}

结果如下:

year: 2015
month: 9
day: 17
1.2 joda-time (推荐)
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Demo {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss");
        LocalDate localDate = formatter.parseLocalDate("2015-09-17 20:27:00");

        System.out.println("yearOfCentury: " + localDate.getYearOfCentury());
        System.out.println("monthOfYear: " + localDate.getMonthOfYear());
        System.out.println("dayOfMonth: " + localDate.getDayOfMonth());
    }
}

结果如下:

yearOfCentury: 15
monthOfYear: 9
dayOfMonth: 17
2. java 8,直接使用 new datetime api (推荐!!)
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Demo {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.parse("2015-09-17 20:27:00", formatter);

        System.out.println("Year: " + ldt.getYear());
        System.out.println("Month: " + ldt.getMonth().getValue());
        System.out.println("DayOfMonth: " + ldt.getDayOfMonth());
    }
}

结果如下:

Year: 2015
Month: 9
DayOfMonth: 17

P.S

    1. java 8 提供的 datetime api 参考了 jodatime,因此两者看起来很相似,使用 java 8 datetime api 时,如果要将日期时间存储到数据库, 还应考虑数据库驱动是否支持该 api
    2. java 7 及之前版本,推荐使用 jodatime, 省时省力省心
posted @ 2016-10-12 17:23  wjj1013  阅读(2621)  评论(0编辑  收藏  举报