java获取指定时间的年月日


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
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页